0
{"0":
    {"id":"276","course":"92","name":"Tutorial - Compound Measures",
    "activitylink":"2490","available":"1331231400","deadline":"1331235000"},
 "1":
    "[email protected]","reference":"[email protected]"}

I am trying to access this in jQuery/Javascript but I unable to. This is my jQuery:

$('#lessonSelect').live('change', function()
{
    $.getJSON('?ajax=true&lid='+$('#lessonSelect').val(), function(data)
    {     
        var len = data.length;      
        var lessonDialog = "";//initialise
        var launchLessonDiv = '<a href="' + data.reference + '">Launch Lesson</a>';

        for (var i = 0; i< len; i++)
        {
            lessonDialog += '<p>' + data[i].name + '</p>'; //get lesson name
        }

        $('#lessonDialog').html(lessonDialog); //insert lesson name into dialog
        $('#launchLessonDiv').html(launchLessonDiv);

    });   
});

This is basically for a select list. Each time the user selects something, links and other stuff on the page change. The stuff works when the page is first loaded but when I start selecting stuff in the select list the lessonDialog comes up blank with nothing inside it.

3
  • can you change the json source format? ...if so that would simplify issue... structure is not consistent between #1 and #2 Commented Mar 9, 2012 at 17:30
  • What do you mean and how would I go about doing that? I am not very good with JSON. In fact, yesterday was the first time I've ever used JSON! Commented Mar 9, 2012 at 17:33
  • would be a lot cleaner if it came out as a pure array [{"name":"foo"},{"name":"bar"}]..post code you are creating it with Commented Mar 9, 2012 at 17:41

1 Answer 1

2

Convert the object with numeric keys to a true array:

$.getJSON('?ajax=true&lid='+$('#lessonSelect').val(), function(data) {   
    data = Array.prototype.slice.call(data);

Your current method fails, because { ... } results in the creation of an object, not an array. The length property of the object is undefined, so the loop would never get started:

for (var i=0; i<undefined; i++) ; // <-- 0 < undefined is always false
Sign up to request clarification or add additional context in comments.

3 Comments

@user1219572 Just in the same way. After converting the object to an array, data is a true array, and array properties & methods can be used.
I've tried alert(data) after data = Array.prototype.slice.call(data) but it alerts nothing :/
@user1219572 Then your server is not sending the data as stated in the question. Set up a stand-alone demo if you need more help.

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.