0

I have a getJSON function that looks like below:

$.getJSON("jsonStats.php?action=segment", function(json) {
    //Loop over each of the values in the jSON response to make the table.
        var tableSegments = '',
            counter = 1;
        $.each(json, function(key, value) {
                tableSegments += '<tr>';
                    tableSegments += '<td></td>';
                    tableSegments += '<td>'+counter+'</td>';
                    tableSegments += '<td>'+value['name']+'</td>';
                    tableSegments += '<td>'+value['y']+'</td>';
                tableSegments += '</tr>';
            counter++;
        });

        $('#segmentTable').empty().append(tableSegments);   
});

The issue that I am running into is that its running the each statement/creating the table before it even gets the data. Is there a way to make it wait until it actually has the jSON data before doing that part?

SBB
  • 8,560
  • 30
  • 108
  • 223

2 Answers2

1

You can use the done callback (jquery.getjson reference) :

$.getJSON('jsonStats.php?action=segment')
.done(function(json)
{
    //Loop over each of the values in the jSON response to make the table.
    var tableSegments = '',
        counter = 1;

    $.each(json, function(key, value)
    {
        tableSegments += '<tr>';
        tableSegments += '<td></td>';
        tableSegments += '<td>'+counter+'</td>';
        tableSegments += '<td>'+value['name']+'</td>';
        tableSegments += '<td>'+value['y']+'</td>';
        tableSegments += '</tr>';
        counter++;
    });

    $('#segmentTable').empty().append(tableSegments);   
})
.fail(function(jqxhr, textStatus, error)
{
    var err = textStatus + ', ' + error;
    console.log( 'Request Failed: ' + err );
});
Anthony Simmon
  • 1,579
  • 12
  • 26
  • The values from the `$.each` just print undefined even though the data is there when I log it – SBB Jun 07 '14 at 01:30
  • @SBB Please look at this : http://stackoverflow.com/questions/733314/jquery-loop-over-json-result-from-ajax-success – Anthony Simmon Jun 07 '14 at 01:34
0

Figured it out..

value['name'] and value['y'] 

need to be value[0] and value[1]

I had the headers as text/javascript on accident this morning so the response was an object, changed it to application/json and thats what made those values change.

SBB
  • 8,560
  • 30
  • 108
  • 223
  • 1
    `$.getJSON` ignores the `Content-type` header, I don't think that has anything to do with it. It sounds like you changed the format of the array in the PHP. – Barmar Jun 07 '14 at 01:38