jQuery ajax inside a loop problem

The problem is that the anonymous callback method captures the ui_item variable by reference. Since there is only one variable, it always gets whatever was assigned last to the variable.

You need to wrap the contents of the for loop in a function that takes i as a parameter, then call the function in the loop. Each call to the wrapper function will create a separate variable, solving the problem.

For example:

function doCheck(i) {
    var split_values = split_files_cb_value_holder[i].split(':');

    var ui_item = split_files_cb_value_holder[i];

    $.ajax({
        type: "POST",
        url: "ds/index.php/playlist/check_folder",
        data: "component_type="+$('#component_type').val()+"&value="+split_values[1],
        success: function(msg)
        {
            console.log(ui_item); //Don't always get the last value
        },
        error: function()
        {
            alert("An error occured while updating. Try again in a while");
        }
    });
}

for (var i = 0; i < split_files_cb_value_holder.length; i++) 
    doCheck(i);

Leave a Comment