Search code examples
javascriptphpjqueryajaxput

jQuery AJAX PUT has empty QUERY_STRING and REQUEST PHP variables


I am writing a web front-end to an existing REST interface which I developed. So far, all my POST and GET requests have been working fine, but when I started adding a PUT request, now I have trouble.

I boiled this down to a very simple test case with 2 files:

My javascript AJAX:

$.ajax({
    url: "putTest.php",
    type: 'PUT',
    dataType: 'application/json',
    data: { testVar: "test" },
    contentType: 'application/json',
    success: function( data ) {

    },
    failure: function( data ) {

    }
});

And my PHP page "putTest.php":

<?php

    var_dump($_SERVER);

?>

I would expect, like in a GET or POST, that my QUERY_STRING server variable would include testVar which is the data I passed to it. However, that is not true, look at the response:

["REQUEST_METHOD"]=> string(3) "PUT"
["QUERY_STRING"]=> string(0) ""
["REQUEST_URI"]=>  string(25) "/test/putTest.php"

What is puzzling me is that I used a Firefox plugin (HttpRequester) and sent the exact same parameters and settings and the response came back perfectly as expected.

Why won't the parameters come across when using the jQuery AJAX?

Thanks!


Solution

  • By default php does not support DELETE/PUT ....

    <?php
    function getRequestParams() {
        if($_SERVER['REQUEST_METHOD'] === "GET" || $_SERVER['REQUEST_METHOD'] === "POST") {
            return $_REQUEST;
        } else {
            // For urlencode
            parse_str(file_get_contents("php://input"), $var);
            // or for json content
            // $var = json_decode(file_get_contents("php://input"));
    
            return $var;
        }
    }
    
    $params = getRequestParams(); 
    

    $params would have your submitted params

    Way you parse would depend on dataType you submit with.