Reputation: 81
I'm trying to pass JSON data from jQuery to PHP so I can overwrite a JSON file. The problem I'm having is that I can't figure out how to tell if the PHP file is receiving my json that I am sending. I'm a bit of a novice..
I currently have this - it's not doing the trick and I'm a bit stuck. Any advice would be great. I am getting alert - 'Right' but nothing from PHP.
var testjson = [{
"name": 1,
"myArray": [{
"0":"1",
"2":"3"
},{
"1":"2",
"3":"4"
}],
"friends":40
}];
$.ajax({
type: "POST",
url: "php/write.php",
data: testjson,
dataType: "html",
contentType : 'application/json; charset=utf-8'
}).done(function(data, status) {
alert('Right');
}).fail(function(data, status) {
alert("Wrong: " + status);
});
$value = json_decode($_POST);
print_r($value);
Upvotes: 0
Views: 89
Reputation: 81
Got it.
Knew it was super simple. Thanks for your help!
$value = $_POST;
print_r($value);
Upvotes: 0
Reputation: 672
Use the below code
var testjson =[{"name":1,"myArray":[{"0":"1","2":"3"},
{"1":"2","3":"4"}],"friends":40}];
var myString = JSON.stringify(testjson);
$.ajax({
type: "POST",
url: "write.php",
data: myString,
dataType: "html"
}).done( function (data, status) {
alert('Right');
})
.fail( function (data, status) {
alert("Wrong: "+status);
});
});
And in php
$json = json_decode(file_get_contents("php://input"));
print_r($json);
Upvotes: 1