Reputation: 784
I am trying to pass JSON data from jQuery ajax to PHP with post method. Then i have to save this data to a text file.
Here is a JSON node in my main object that i want to submit to PHP. I captured this image from Chrome's console because i am lazy.
This is the javascript code that makes the call:
function save(data, backup, notify, clear) {
$.ajax({
type: "POST",
url: "user.php?action=save&backup="+backup,
data: data,
async: false,
success: function(result){
console.log(result);
},
error:function(e){
console.log(console.log(e));
}
});
}
And then when i try to var_dump this $_POST data in my php, the output looks like below:
var_dump($_POST);
// save
file_put_contents($file, json_encode($_POST,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
As you can see the "files" node disappears. Why? How can i pass empty nodes to PHP? I need "files" node only with key. I will add some values after some time ago.
In JS:
data: {"data": JSON.stringify(data) },
In PHP:
$data = json_decode(stripslashes($_POST['data']));
file_put_contents($file, json_encode($data, JSON_PRETTY_PRINT));
Upvotes: 0
Views: 712
Reputation: 16526
The problem is that your object is not what jQuery considers a PlainObject
Here is an example:
var obj = {"c":{}};
var arrayOfObjects = [obj];
jQuery.isPlainObject(arrayOfObjects); // false
See the [
at the beginning if the screen?
This is the documentation for the $.ajax data
field
data Type: PlainObject or String or Array Data to be sent to the server. It is converted to a query string, if not already a string. It's appended to the url for GET-requests. See processData option to prevent this automatic processing. Object must be Key/Value pairs. If value is an Array, jQuery serializes multiple values with same key based on the value of the traditional setting (described below).
Here is what jQuery has to say about the traditional setting.
Note: Because there is no universally agreed-upon specification for param strings, it is not possible to encode complex data structures using this method in a manner that works ideally across all languages supporting such input. Use JSON format as an alternative for encoding complex data instead.
You can fix the problem by doing the following:
$.ajax({
type: "POST",
url: "user.php?action=save&backup="+backup,
data: JSON.stringify(data),
// ...
});
For the record PHP does not have a problem with empty JSON objects
$json = json_decode('{"c":{},"b":2}');
var_dump(json_encode($json,JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT));
// output
string(33) "{
"c": {
},
"b": 2
}"
Upvotes: 1