0

I am having a little trouble retrieving the values from a JSON object that is returned after a jQuery GET request and I am hoping someone here will be able to help. I think I may be doing something stupid but cannot figure it out.

In firebug the response is show as:

[{"plan_id":"2","plan_name":"plan 2","plan_desc":"plan 2 desc"}]

However when I try to retrieve the values they are undefined.

Here is the code I am using:

jQuery(function(){
jQuery("#add_plan").click(function(){
var val = jQuery("#plan_id").val();
if (!isNaN(val))
{
      jQuery.ajax({
      success: function(data) {
        if (data)
        {

         jQuery("#plan-list").append(
"<li>"
+ " <label for=\"plans\">" + data.plan_name + "</label>"
+ "</li>"
); 
        }
      },
      type: 'GET',
          dataType: 'json',
          url: 'http://example.com/plans.php?plan=' + val 
      });
}
});
});

Any help would be appreciated.

Thanks

Paul

3 Answers 3

4

Since it's an array, you need data[0].plan_name instead, or possibly a loop like this if you expect multiple results:

$.each(data, function() {
  $("<label for='plans' />").text(this.plan_name).wrap("<li />").parent()
    .appendTo("#plan-list");
});

You can give it a try here.

Sign up to request clarification or add additional context in comments.

Comments

3

Looking closely, your JSON result

[{...}]

is an object ({}) inside an array ([]).

You will be able to access the values using

data[0].plan_name

Comments

0

The above posters are correct, but don't assume there will always be an Array, test the value of data every time. If it's an object, proceed. If it's an object/array loop.

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.