Reputation: 6511
In $(document).ready I am making in ajax request in a function, which returns json data which I add to an array. I am returning the array from that function but when I try to assign whats returned to another array my alert doesn't show an array full of values.
function retrieveGroupNames() {
var rows = new Array();
$.ajax({
type: "POST",
url: '@Url.Action("LookUpGroupName", "UserManager")',
dataType: "json",
data: {},
success: function (data) {
for (var i = 0; i < data.length; i++) {
rows[i] = {
data: data[i],
value: data[i].group,
result: data[i].group
}
// alert(data[i].group);
// alert(data[1].group);
} // end of for loop
// alert(rows[1].value);
} // end of success
}); // end of ajax
// alert(rows); data here
return rows;
} // end of function
$(document).ready(function () {
chkSelection();
var rows = [];
rows = retrieveGroupNames();
alert(rows);
});
Some help please? Thanks!
Upvotes: 0
Views: 250
Reputation: 46647
The other option other than the callback provided in ThiefMaster's answer is to use $.Deferred
objects. Using deferreds gives you control over when and what should happen during asynchronous processing, such as ajax calls.
function retrieveGroupNames() {
// create a deferred object
var deferred = new $.Deferred();
$.ajax({
...
success: function(data) {
var rows = [];
for(var i = 0; i < data.length; i++) {
rows[i] = {
data: data[i],
value: data[i].group,
result: data[i].group
}
}
// resolve the deferred and pass the rows as data
deferred.resolve(rows);
}
});
// return a promise
return deferred.promise();
}
$(document).ready(function () {
// use the when...then syntax to consume the deferred function
$.when(retrieveGroupNames()).then(function (rows) {
// do whatever you want with rows
});
});
Also note that $.ajax
already returns a promise itself, so you could just say return $.ajax({...});
in your retrieveGroupNames
function.
Upvotes: 1
Reputation: 318488
AJAX is asynchronous. You can't return stuff that relies on the request being finished. You need to use a callback instead:
function retrieveGroupNames(callback) {
$.ajax({
type: "POST",
url: '@Url.Action("LookUpGroupName", "UserManager")',
dataType: "json",
data: {},
success: function(data) {
var rows = [];
for(var i = 0; i < data.length; i++) {
rows[i] = {
data: data[i],
value: data[i].group,
result: data[i].group
}
}
callback(rows);
}
});
}
$(document).ready(function() {
chkSelection();
retrieveGroupNames(function(rows) {
alert(rows);
});
});
Upvotes: 3