phpajaxcurl

PH cURL Request with AJAX works on URL but not on the response


I'm sending a value from a form to an ajax request which runs a cURL process on my website. I test the response back and it works perfectly. But when it goes back to AJAX, it gives a 400 error.

Ajax Request:

<script type="text/javascript">
$( document ).ready(function() {
        $("#button-addon2").click(function () {
            alert("sbox = " + $("#sbox").val());
            $.ajax({
                url: "calcsave.php?ajtype=23&q=" + $("#sbox").val(),
                context: document.body,
                success: function (t) {
                alert("t = " + t);
                    $("#calcchat").append(t);
                },
            });
        });
});
</script>

PHP processes the ajax:

       case 23:
    //ini_set('display_errors', '1');
    //ini_set('display_startup_errors', '1');
    //error_reporting(E_ALL);
    $q = $_GET['q'];
    // $_GET['secret']=='mc-api-654'
    //echo "q = " . $q . "<br />";
    $ch = curl_init();
    $url = "https://www.mathcelebrity.com/search.php?q=" . $q . "&secret=mc-api-654";
    //echo "url = " . $url . "<br />";
    $_SESSION['api'] = 1;
    curl_setopt($ch,CURLOPT_URL,$url);
    curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,2);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
    //curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1); 
    //curl_setopt($ch, CURLOPT_HEADER, 1);
    $result = curl_exec($ch);
    curl_close($ch);
    if (empty($result)){
        echo "Nothing returned from url.";
    }
    else{
        //echo "success";
        // when we echo result, it prints full MC page with menus. Maybe try json format?
        echo $result;
    }
break;

Output URL for the PHP piece which works if you paste it into a browser

But when it comes back to AJAX, it shows a 400 error.

I'd like to pick up the text and html from the url above and drop it back into the AJAX on the return.


Solution

  • Solved it! I have to trim out the $_GET['q'] because that may causes spaces in the URL. Thanks everybody.