0

This jQuery code is working:

$.ajax({
    type: "POST",
    url: "file.php",
    data: { json: json },
    complete: function (data) {
        var result = data.responseText;
        console.log(result); // logs 'echo' from PHP file
    }
});

This JavaScript code is still not working:

var xhr = new XMLHttpRequest();
xhr.open("POST", "file.php", true);
xhr.setRequestHeader('Content-Type', 'application/json');
xhr.onreadystatechange = function () {
    if (xhr.readyState == 4 && xhr.status == 200) {
        var result = xhr.responseText;
        console.log(result); // supposed to log 'echo' from PHP file
    }
}
xhr.send(JSON.stringify(json));

Aren't these two approaches equivalent, or am I missing something?

Suppose 'file.php' looks something like this:

if(isset($_POST['json'])){
 $obj = json_decode($_POST['json']);
 //some php operation
 // echo $obj keys and values
}
20
  • 1
    You must call setRequestHeader() after open() developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest Commented Jul 25, 2016 at 22:42
  • 2
    The request header might be wrong (might have to be application/json) but I'm pretty sure you have to stringify your json: xmlHttp.send(JSON.stringify(json)); Commented Jul 25, 2016 at 22:43
  • 1
    codepen.io/anon/pen/PzZLaJ Commented Jul 25, 2016 at 23:01
  • 1
    Try this: xhr.send(JSON.stringify({json:json})); Commented Jul 25, 2016 at 23:03
  • 1
    @Wagtail yeah wagtail when you stringfy json you need to make sure it represents a javascript object. so by make an object of { 'key' : 'value'} JSON.stringify will make that into a valid json string. json_decode will work as long as you have a properly formatted json string. Commented Jul 25, 2016 at 23:04

1 Answer 1

1
data : { json: json } 

gets serialized to '{ "json": {data} }'

JSON.stringify(json)

gets serialized to '{data}' and there is no "json" key

add your javascript object to a parent wrapper object with a "json" key

JSON.stringify({ json: json });
Sign up to request clarification or add additional context in comments.

2 Comments

This was the solution for correctly passing the json string to the PHP function for json_decode($_POST['json']) but did not address why the JavaScript was not returning the same console.log() value as the jQuery function.
if you set the $.ajax dataType to "text" they should be the same. When its missing $.ajax will guess the return type based on its content and may process the data before returning it to you. see: api.jquery.com/jquery.ajax [settings-dataType]

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.