tags:

views:

36

answers:

3

Hi Guys,

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  A: 

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.

Nick Craver
+2  A: 

Looking closely, your JSON result

[{...}]

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

You will be able to access the values using

data[0].plan_name
Pekka
A: 

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.

AutoSponge