POST, AJAX, And PHP : JSON Submission
Ok, so here is my JS/jQuery code, my rate.php file simply has a print_r($_POST) in it. The problem is, the $_POST is accepting rated as the string 'Array', rather than the actual
Solution 1:
When passing JSON data to your php script through ajax I would recommend string encoding the JSON data and then parsing it on the server side.
var rated = {"key" : key , "value" : value};
var rated_encoded = JSON.stringify(rated);
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: {
"rated" : rated_encoded
},
success: function(data) {
alert(data);
}
});
Then you should be able to access the POST variable in your PHP script using $_POST as with any other scalar value. Once you have the JSON string 'rating_encoded' on the server-side, parse it to an associative array using PHP's json_decode().
if(isset($_POST["rated"])){
$rated_json = $_POST["rated"];
$JSONArray = json_decode($rated_json, true); //returns null if not decoded
//Values can now be accessed like standard PHP array
if($JSONArray !== null){
$key = $JSONArray["key"];
$value = $JSONArray["value"];
}
}
I've found that this method is very effective for transferring javascript object data to the server and vice versa (using PHP's json_encode() to translate PHP arrays into valid javascript objects)
Solution 2:
It is a proper array, just not what you expect it to be. What you likely want can be achieved by simply passing rated
to the data
parameter as is. I.e.
var rated = {"key" : key , "value" : value};
$.ajax({
type: "POST",
url: $(location).attr('protocol') + "//" + $(location).attr('hostname') + "/ajax/rate.php",
data: rated,
success: function(data) {
alert(data);
}
});
Post a Comment for "POST, AJAX, And PHP : JSON Submission"