Reputation: 9647
I am trying to retrieve the following json generated in my php script uing jquery. However, I am not being able to display it. If I alert it, it just displays 'undefined'. Using $('#demo').html(data.htmlOutput) to display the html doesn't do anything either. Please can someone point out what I'm doing wrong?
$arr = array('htmlOutput' => '<b>hello</b>', 'no_rows' => 'balh');
echo json_encode($arr);
$.post('get-offers.php', $("#offerForm").serialize(), function(data) {
alert (data.htmlOutput);
alert (data.no_rows)
$('#demo').html(data.htmlOutput);
}
I can see the json response in the FB console,however, it still does nothing.
Upvotes: 1
Views: 220
Reputation: 6780
Two options:
First, set 'json' as the last parameter of you $.post
to tell it that it is expecting a JSON response.
Second, before your first alert, add this:
var obj = jQuery.parseJSON(data);
Then alert(obj.htmlOutput);
See if that works for you
Upvotes: 0
Reputation: 150253
You Have tell jquery you are expecting json
object, do it with the dataType as follows:
.post('get-offers.php', $("#offerForm").serialize(), function(data) {
alert (data.htmlOutput);
alert (data.no_rows)
$('#demo').html(data.htmlOutput);
},'json'); //<====
dataType: The type of data expected from the server.
I would think jquery will be able to guess it is a json
object, because in their docs written:
Default: Intelligent Guess (xml, json, script, text, html).
Well, I guess that that guess isn't that Intelligent... =)
Upvotes: 2
Reputation: 11779
Tell jquery that you're expecting json, it's the last argument:
$.post('get-offers.php', $("#offerForm").serialize(), function(data) {
alert (data.htmlOutput);
alert (data.no_rows)
$('#demo').html(data.htmlOutput);
}, "json");
Upvotes: 3