0

I am trying a simple test to learn about the JQuery Ajax POST method and I have setup a little example on my server. However I can't it to work.

My JavaScript is as follows:

JavaScript:

var json = {"Num String":"2","Num":3,"Num":11,"Num":2,"Num":"?"};
$.ajax({
        type: "POST",
        url: "sampleJSONPost.php",
        data: json, //Data to POST to the server
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        error: function (jqXHR, status, err) {
            console.log("Error " + err + " " + status + " " + JSON.stringify(jqXHR)); //Log the Error 
        },
        success: function (data, status, jqXHR) {  
              console.log(JSON.stringify(data)); //Log the Data returned
              $("span").text(data);
        }
    });
};

And here is my PHP:

PHP:

<?php
$data = $_POST["data"];
echo json_decode($data);
?>

However this always gives me the following error:

Error SyntaxError: Unexpected end of input parsererror {"readyState":4,"responseText":"","status":200,"statusText":"OK"} 

So to me it looks like my $data variable in PHP is not getting the JSON I am sending with the POST, would this be correct? If so can anyone help me find what is wrong? I have already tried lots of other solutions from SO but without success so I must be missing something simple?

3 Answers 3

6

Change into

var json = {"data":{"Num String":"2","Num":3,"Num":11,"Num":2,"Num":"?"}};
Sign up to request clarification or add additional context in comments.

3 Comments

Or at server side $data = $_POST;
remove dataType: "json" line from your ajax config
and contentType: "application/json; charset=utf-8", also
1

Change

      data: json,

to

    data: JSON.stringify({ json : json }),

Comments

1

Try this

var json = {{"Num String":"2"},{"Num":3},{"Num":11},{"Num":2}};

or

This, I am not checking

$.ajax({
    type: 'POST',
    url: 'sampleJSONPost.php',
    contentType: 'application/json; charset=utf-8',
    data: { "Num String":"2","Num":3,"Num":11,"Num":2,"Num":"?" },
    dataType: 'json',
    success: function(data)
{

},
    error: AjaxFailed
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.