Search code examples
phppostjquery-mobileis-empty

JQuery Mobile POST data empty in $_POST


I'm running into a problem with JQuery Mobile (new to me) and the AJAX-call. I'm using the following code:

$.ajax({
            type: "POST",
            url: "http://**correct url**/post/todoitem",
            beforeSend: addHeaders,
            dataType: "json",
            contentType: "application/json",
            data: { "todoitem":"test" }, // this is just as a test
            success: function(result) {
                alert("Success: " + JSON.stringify(result));
            },
            error: function() {
                alert("Error: " + JSON.stringify(arguments));
            }
        });

While executing this, it calls a PHP script where I need the data from the todoitem, so in this case the string "text" (in the end, multiple variables are to be send, but for now I'm just using one parameter for simplicity).

My PHP code looks like this (also just for testing purposes):

echo json_encode($_POST));

The result is: nothing, null. The $_POST seems to be empty. I've searched and tried many things, but most answers (even here on stackoverflow) are about forms and people say I need to serialize the contents of the form. However, I'm not using a form at all.

I also tried

data: JSON.stringify({ "todoitem" : "test" })

as some suggested but this did not work either. I do know that the data is being transfered because of this little PHP hack I tried:

echo file_get_contents('php://input');

That exactly shows the data: todoitem = test. So where does this all go wrong? I'm working on this for days now! Thnx in advance


Solution

  • The problem is with this part of your code:

    contentType: "application/json",`
    

    Removing that line should make the sent Content-Type header default to application/x-www-form-urlencoded and PHP will decode the request into $_POST.