i have this simple script:
function paginateUsers(page){
get( _config_remote_host+'/users?page='+page,function(json){
json = JSON.parse(json);
var _html = "";
var json_users;
var json_num_users;
if(json.users){
json_users = json.users;
json_num_users = json.number_of_users;
}
if(!json.users){
json_users = json;
json_num_users = 0;
}
for(i = 0; i < json_users.length; i ++){
if(i == 0){ _html += '<div class="row-fluid separator20">';}
_html += '<div class="span3 media userbox">'
+'<div class="row-fluid">'
+ '<div class="span3">'
+ ' <a class="thumbnail" href="#">'
+' <img src="jon.png" alt=""/>'
+' </a>'
+' </div>'
+'<div class="span9">'
+' <ul class="unstyled">'
+' <li><strong><a href="user.html?id='+json_users[i].id+'">'+json_users[i].first_name+'</strong></br>'+json_users[i].last_name+'</a></li>'
+' <li><h6>New york city</h6></li>'
+' <li><a class="pull-right btn btn-mini">Contact</a></li>'
+' </ul>'
+' </div>'
+' </div>'
+'</div>';
if(i%3 == 2){ _html += '</div><div class="row-fluid separator20">';}
}
$('.users-list').html(_html).hide().fadeIn(100);
//return always total users number to calculate total links number
return json_num_users;
});
}
then i do
var n = paginateUsers(1);
alert(n)
but it alerts always ‘undefined’ , what’s the real problem here?
here the ajax call and init functs:
function createCORSRequest(_method, _url){
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(_method, _url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(_method, _url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
/*END INIT FUNCTION*/
function get(_url, _callback){
var xhr = createCORSRequest('GET',_url);
if (!xhr){
throw new Error('CORS not supported');
}
$('.ajax-loading').show();
xhr.send();
/*SUCCESS -- do somenthing with data*/
xhr.onload = function(){
// process the response.
_callback(xhr.responseText);
$('.ajax-loading').hide();
};
xhr.onerror = function(e){
console.log(e);
$('.ajax-loading').show();
};
}
thanks
You cannot return from an AJAX call, it’s asynchronous. Your return is inside the callback function, which runs at some point in the future, when the AJAX call is done.
paginateUsersdoesn’t actually return anything (which means it returnsundefined).Instead of trying to return anything, you should do all actions related to the data inside the callback. Or, better yet pass a callback function, and call that when you’re done.
Then you can do this: