I\'m having trouble figuring out how to properly read my JSON response from a jQuery $.post() request.
In the below jQuery code, I populate an associative array of s
Ok then..the data object you're getting back from the post is: {"id":"abc","images":[{"color123":"somelink.com\/123","color223":"somelink.com\/223"}]};
If you change your alert, you'll find the values you're looking for:
$.post(
"test.php",
{ id: product_id, "images[]": jQuery.makeArray(image_links) },
function(data) {
var response = jQuery.parseJSON(data);
var images = response.images[0];
for (var i in images){
alert(images[i]);
}
}
);
$.post expects xml by default, you need to specify the response format
$.post(
"test.php",
{ id: product_id, images : jQuery.makeArray(image_links) },
function(response) {
// Response is automatically a json object
for(var i = 0; i < response.images.length; i++) {
alert(response.images[i]);
}
}, 'json' // <-- HERE
);
Also, consider adding a content type header in your php script
<?php
header("Content-type: application/json"); // Adding a content type helps as well
$product_id = $_POST['id'];
$images = $_POST['images'];
$response = array();
$response['id'] = $product_id;
$response['images'] = $images;
echo json_encode($response);
?>
A pretty basic example would be something like :
$.post('test.php', {"id": 42}, function (json) {
console.log(json);
}, 'json');
PHP example
$number = rand(1,$_POST["id"]);
return print json_encode($number);