user1038814
user1038814

Reputation: 9647

Can't display returned JSON when using Jquery

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

Answers (3)

Barry Chapman
Barry Chapman

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

gdoron
gdoron

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.

docs

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

driangle
driangle

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

Related Questions