1

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.

4
  • How does the script know to parse it as JSON? Commented Feb 8, 2012 at 17:13
  • @BarryChapman. It should have known, see my answer below. Commented Feb 8, 2012 at 17:23
  • @gdoron - I was applying 'redirection'. I was hoping he might realize that he wasn't telling the script that it expected json and could have found the answer :) Commented Feb 8, 2012 at 17:23
  • @BarryChapman. jQuery team say in their docs they are doing Intelligent Guess by default... so it could have worked... Commented Feb 8, 2012 at 17:25

3 Answers 3

3

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");
Sign up to request clarification or add additional context in comments.

Comments

2

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... =)

Comments

0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.