Reputation: 1005
I am trying to pass an array I am creating in PHP using json_encode()
. I am running an AJAX request, see as follows:
AJAX CALL:
$.ajax({
type: "POST",
url: "../includes/ajax.php?imagemeta=1",
data: {
'id' : $(this).attr('id')
},
datatype:"json",
success: function(data) {
console.log(data);
console.log(data["image_height"]);
},
error: function(data) {
console.log(data);
}
});
PHP JSON RESPONSE:
if(isset($_GET["imagemeta"])){
$id = intval($_POST["id"]);
$path = "../uploads/images/" . $fm->selectImageById($id);
$meta = array();
list($width, $height) = getimagesize($path);
$meta["image_height"] = $height . 'px';
$meta["image_width"] = $width . 'px';
print json_encode($meta);
}
Although, the console.log(data) returns the following: {"image_height":"1374px","image_width":"920px"}
The following line console.log(data["image_height"]) returns undefined.
I have tried multiple attempts and have read through majority of the top rated questions regarding the subject. I am fairly new with JSON encoding so please inform me if I have a misunderstanding somewhere.
Upvotes: 1
Views: 75
Reputation: 613
Either set php JSON response header or return plain text from php and use $.parseJSON in success function.
success: function(data) {
jSon = $.parseJSON(data);
console.log(jSon.image_height);
}
Upvotes: 0
Reputation: 2677
If console.log displaying you following:-
{"image_height":"1374px","image_width":"920px"}
Then you can access "image_height" as follows:-
data.image_height;
Upvotes: 0
Reputation: 781004
datatype:"json",
should be:
dataType:"json",
^
Javascript is case-sensitive.
Upvotes: 4