0

I've gotta problem with filling javaScript array using an Ajax request. here is my code. Ajax part is working properly.

function GetColumns()
{
    var x = [];
    $.ajax({
        url: '@Url.Content("~/AreaModel/GetColumns")',
        data: {
            'id': 10, 
        },
        dataType: "json",
        type: 'POST',
        success: function (data) {
            debugger;
            var item = data.list;
                for (var i = 0; i < data.count; i++) {
                    var val = item[i];
                    x.push({ field: "row.Col1.comNm", title: " " });
                }
        },
        error: function () {
            alert("error!");
        }
    });

    var n = $("#secret").val(x);

    for (var i = 0; i < 10; i++) {
        //x.push({field: "row.Col1.comNm", title: " " });
    }


    return (x);

}

I have debugged the function with fire bug. here is the screen shot. After the end of the ajax function, x[] become null. I have no idea what's happens to the data. Please help me.. enter image description here

tishantha
  • 487
  • 5
  • 13
  • 34
  • Try `console.log(x)` after ajax call and check the content on console. – Aditya Singh Nov 29 '13 at 03:44
  • 1
    you are returning the `x` variable at the end of the function, but the actual push happens in the success asynchronously, which executes much later, you should return some type of promise that resolves after the actual data has been received – Kris Ivanov Nov 29 '13 at 03:51
  • you can't return `x` from `GetColumns` because it uses a async method to populate x – Arun P Johny Nov 29 '13 at 03:52

2 Answers2

3

you can't return x from GetColumns because it uses a async method to populate x.

The solution is to use a callback mechanism which will invoke a function once the column details are fetched asynchronously.

function GetColumns(callback) {
    return $.ajax({
        url: '@Url.Content("~/AreaModel/GetColumns")',
        data: {
            'id': 10,
        },
        dataType: "json",
        type: 'POST'
    }).done(function (data) {
        debugger;
        var array = $.map(data.list, function (item) {
            return {
                field: "row.Col1.comNm",
                title: " "
            }
        });
        callback(array)
    }).fail(function () {
        alert("error!");
    });
}

then

GetColumns(function(columns){
    //do whatever you want to do with column here
})

instead of

var columns  = GetColumns();
//do stuff
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531
1

.ajax is asynchronous, that means the success callback will be executed only after you get a successful response, meanwhile GetColumns could reach it's end.

If GetColumns reaches it's return statement before you get the response, then x will be empty.

You shouldn't try to return x in GetColumns since there's no certainty that you'll get the response in time.

Any processing of the response's data should be confined to the success callback.

pgpb.padilla
  • 2,318
  • 2
  • 20
  • 44