4

I'm getting json data from ajax and think I'm close to getting this done, but for some reason my UL isn't populating and I can't find any debug info to help.

Can someone point me in the right direction?

json data : 

{"data":[{"racer_id":73,"racing_nbr":"4","entry_id":131},
{"racer_id":9,"racing_nbr":"48","entry_id":132},
{"racer_id":525,"racing_nbr":"7","entry_id":133},
{"racer_id":534,"racing_nbr":"11","entry_id":134},
{"racer_id":213,"racing_nbr":"72","entry_id":135},
{"racer_id":574,"racing_nbr":"66f","entry_id":136}]}


$('.list-group-item').click(function() {
var data = 'class_id='+ $(this).attr('rel') + '&event_id=' +<?php echo $_GET['event_id']; ?>
// POST to server using $.post or $.ajax
$.ajax({
    data: data,
    type: 'GET',
    dataType: 'JSON',
    url: 'php/builder/getRidersScoringHeats.php',
    success: function(data) {
      var obj = data,  // get entry object (array) from JSON data
      ul = $("#sortable");                    // create a new ul element
        // iterate over the array and build the list
          for (var i = 0, l = obj.length; i < l; ++i) {
            ul.append("<li class='ui-state-default' id='item-" + obj[i].entry_id + "'>" + obj[i].racing_nbr + " - " + obj[i].racer_id + "</li>");
          }
      $("#sortable").append(ul);    // add the list to the DOM
  }
 });
});

Any help would be greatly appreciated.

Thanks in advance.

indymx
  • 343
  • 2
  • 10

2 Answers2

3

In your case data actually contains an object named data which is an array collection of objects.

So to do this easily:

$.each(data.data, function(i, info){
    ul.append("<li class='ui-state-default' id='item-" + info.entry_id + "'>" + info.racing_nbr + " - " + info.racer_id + "</li>");
});
Ohgodwhy
  • 49,779
  • 11
  • 80
  • 110
2

If data is an object that gets assigned to obj, then your problem is that obj.length doesn't resolve to any value. Objects don't have a length property. You'll need to either put the data in an array at the top level, or use a library like underscore.js to get the ability to do that.

Alternatively, see this answer: Length of a JavaScript object

Community
  • 1
  • 1
user86577
  • 21
  • 3