Wagtail Wagtail - 1 year ago 88
Ajax Question

jQuery vs. JavaScript ajax 'POST' functions

This jQuery code is working:

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

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

Suppose 'file.php' looks something like this:

$obj = json_decode($_POST['json']);
//some php operation
// echo $obj keys and values

Answer Source
data : { json: json } 

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


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 });
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download