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
}
zdebruine
  • 2,665
  • 5
  • 24
  • 47
  • 1
    You must call setRequestHeader() after open() https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest – Nitin Jul 25 '16 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));` – Will Jul 25 '16 at 22:43
  • @Will good catch, I bet I need to do that, but didn't fix it. – zdebruine Jul 25 '16 at 22:45
  • @Nitin I am calling setRequestHeader('Content-Type','...'); -- was this not what you were thinking? – zdebruine Jul 25 '16 at 22:46
  • http://stackoverflow.com/questions/477816/what-is-the-correct-json-content-type – Will Jul 25 '16 at 22:48
  • @Will yep, agreed. I changed application/json and am doing JSON.stringify(json). See edited code which is still not working. – zdebruine Jul 25 '16 at 22:49
  • @Wagtail I think I misread the question. could you update the question with the new changes? Else try without setRequestHeader – Nitin Jul 25 '16 at 22:52
  • @Nitin I've done so. – zdebruine Jul 25 '16 at 22:53
  • Hold up...you are sending {json:json} in first case, in 2nd case it is a string without key, or i am wrong...how are you handling the json on server side and what do you see on server side? To answer your question, i think in this case you are sending two different json data. – Nitin Jul 25 '16 at 22:56
  • @Nitin I've edited it. – zdebruine Jul 25 '16 at 22:59
  • What is not working on it? Do you get an error? Copying and pasting your code directly said json was not defined. Once I create a json var of var json = {'key' : 'value'}; and pasted your code i nthe console it shot off an ajax request to file.php. – JD E Jul 25 '16 at 22:59
  • @JD E would you mind posting that quick? – zdebruine Jul 25 '16 at 23:00
  • 1
    http://codepen.io/anon/pen/PzZLaJ – JD E Jul 25 '16 at 23:01
  • if you use your dev tools you can see the ajax request fire off. – JD E Jul 25 '16 at 23:02
  • "not working". Specifically, what is not working? – Josh Beam Jul 25 '16 at 23:03
  • @JD E yep, I do. I guess I should work with it and see if json_decode works as well. – zdebruine Jul 25 '16 at 23:03
  • 1
    Try this: xhr.send(JSON.stringify({json:json})); – Nitin Jul 25 '16 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. – JD E Jul 25 '16 at 23:04
  • @JD E Yes I think that was my issue. Thanks!! – zdebruine Jul 25 '16 at 23:06
  • @Wagtail i like this [site](http://www.jsoneditoronline.org/) to help build json, especially in complex objects. – JD E Jul 25 '16 at 23:07

1 Answers1

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 });
Steve
  • 1,906
  • 2
  • 14
  • 23
  • 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. – zdebruine Jul 26 '16 at 01:07
  • 1
    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: http://api.jquery.com/jquery.ajax/ [settings-dataType] – Steve Jul 26 '16 at 01:53