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.
Solution:
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));