Wagtail Wagtail - 4 months ago 10
Ajax Question

jQuery vs. JavaScript ajax 'POST' functions

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
}

Answer
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 });