swissphp
swissphp

Reputation: 81

TypeError: Cannot read property 'length' of undefined - but don't even use 'length'!

I have read all over the web about this kind of error, and established it's not from having multiple jQuery core sources. I am using jQuery-1.10.2.min.js.

The page I am working on allows the user to select an Event from a list, after which the list of Activities belonging to that Event should be displayed on the page.

The jQuery/Ajax code reads:

$("#event").change(function ()
{
    //get the selected value
    var eventId = $(this).val();
    alert( "sel val is " +  eventId);//this works

    $.ajax({
        dataType: 'json',
        type: 'GET',
        url: 'stcg-json-responses.php?fct=getJSONAllActivitiesAtEvent',
        data: "eventId="+eventId,
        cache: false,
        success: function(data)
        {
                alert("Data sent! " + eventId);//this works

                $.isArray(data.response)
                {
                    alert("this is an array");//this works
                    $.each(data.response, function (index, value)
                    {
                        // Loop through your results in jQuery and modify your HTML elements
                        htmlElement.append("<option id='key'>" + value + "</option>");
                    });
                }
        },
        error: function(xhr, status, error)
        {
            alert("Data not sent!");
            //console.log("Data not sent!");
        }
    });

Looking at the results with various browser dev tools, the Response is always fine - it is in the form of an anonymous array of JSON objects, each one comma-separated from the other. But the script above crashes on: $.each(data.response, function (index, value)

with the Uncaught TypeError.

To give you a better idea, the Response data is formatted as (for example):

[
{"activity_id":44,"activity_name":"Unknown activity","activity_desc":"Unknown activity","activity_short_code":"U","event_id":4,"capacity":0,"day_of_week":6,"date":"2012-03-24","project_leader":"","open":0},
{"activity_id":87,"activity_name":"Cleanup at Zoo Bellevue","activity_desc":"Zoo et parc d'accueil Bellevue","activity_short_code":"","event_id":4,"capacity":5,"day_of_week":6,"date":"2012-03-24","project_leader":"","open":0},
{"activity_id":89,"activity_name":"Ali Baba cleanup","activity_desc":"Ali Baba cleanup","activity_short_code":"","event_id":4,"capacity":10,"day_of_week":6,"date":"2012-03-24","project_leader":"","open":0}
]

Anyone have some idea what is going on here? Thanks so much, swissphp

P.S. Have tried with a plain Javascript for loop, but it crashes on array.length.

==================================================================================== SOLUTION - BASED ON HELP RECEIVED HERE, this is my new code, which works:

$("#event").change(function ()
{
    //get the selected value
    var eventId = $(this).val();

    var selectElement = $("#activity");

    $.ajax({
        dataType: 'json',
        type: 'GET',
        url: 'stcg-json-responses.php?fct=getJSONAllActivitiesAtEvent',
        data: "eventId="+eventId,
        cache: false,
        success: function(data)
        {
            if ($.isArray(data))
            {
                $.each(data, function (index, value)
                {
                    // Loop through your results in jQuery and modify your HTML elements
                    selectElement.append($('<option></option>').val(index).html(value['activity_name']));
                });
            }
        },
        error: function(xhr, status, error)
        { //etc etc etc

Many thanks to all who contributed!

Upvotes: 1

Views: 5436

Answers (1)

Anthony Grist
Anthony Grist

Reputation: 38345

You're attempting to call $.each() on undefined, which results in that error. From the jQuery source:

each: function( obj, callback, args ) {
    var value,
        i = 0,
        length = obj.length,
        isArray = isArraylike( obj );

Or, in other words, data.response isn't defined in the JSON returned by your server. I suspect the problem is that you've missed out the if statement.

$.isArray(data.response)
{
    alert("this is an array");//this works
    $.each(data.response, function (index, value)
    {
        // Loop through your results in jQuery and modify your HTML elements
        htmlElement.append("<option id='key'>" + value + "</option>");
    });
}

That's a meaningless statement ($.isArray(data.response)) followed by an unconditional block of code. You likely meant:

if($.isArray(data.response))
{
    alert("this is an array");//this works
    $.each(data.response, function (index, value)
    {
        // Loop through your results in jQuery and modify your HTML elements
        htmlElement.append("<option id='key'>" + value + "</option>");
    });
}

Upvotes: 4

Related Questions