I have the following 'stringified' JSON data:
$jsonData = '[{"tnum":"1","tnam":"Title1","snum":"24","word1":"this","word2":"is fun"},{"tnum":"343","tnam":"Title2","snum":"233","word1":"hello","word2:"again"}]'
My AJAX is:
$.ajax({
url: "doSave3.php",
type: "POST",
data: jsonData,
contentType: 'application/json; charset=UTF-8',
success: function() {
alert("Data saved");
},
error: function() {
alert("Data were not saved");
}
});
And the PHP on the server side is:
if(isset($_POST['data'])){
$jsonData = $_POST['data'];
$result = json_decode($jsonData);
foreach ($result as $key => $value) {
if ($value) {
$sql = "INSERT INTO saved_lists (id, title_number, title_name, sub_number, word1, word2) VALUES (NULL, $value->tnum, '$value->tnam', $value->snum, '$value->word1', '$value->word2')";
mysql_query($sql);
}
}
}
I've tested the PHP and it works when I set manually set $jsonData inside doSave3.php. Note that when doing this test, I also have to remove if(isset($_POST['data'] or it won't get past the if statement. When I revert back to relying upon $_POST['data'] there is no action so I am pretty sure doSave3.php is not receiving the POST data.
Some help would be appreciated. I've gone over all the similar posts and corrected a few things, but no dice as yet.
Ahh.. the problem is with your json string. you are missing a double quotes at the end of the string "word2:"again"
this should be "word":"again"
.
var jsonData = '[{"tnum":"1","tnam":"Title1","snum":"24","word1":"this","word2":"is fun"},{"tnum":"343","tnam":"Title2","snum":"233","word1":"hello","word2":"again"}]';
$.ajax({
url: "echo.php",
type: "POST",
data: 'data='+jsonData,
success: function(data) {
alert(data);
},
error: function() {
alert("Data were not saved");
}
});
});
and in echo.php
$json = urldecode($_POST['data']);
var_dump(json_decode($json));
Everything works fine with the double quotes.:)