Filippo oretti
Filippo oretti

Reputation: 49843

Simple jquery ajax return

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

Upvotes: 1

Views: 412

Answers (3)

gen_Eric
gen_Eric

Reputation: 227290

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. paginateUsers doesn't actually return anything (which means it returns undefined).

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.

function paginateUsers(page, callback){
    get( _config_remote_host+'/users?page='+page,function(json){
        // code...
        if(typeof callback === 'function'){
            callback(json_num_users); // Instead of "return json_num_users;"
        }
    });
}

Then you can do this:

paginateUsers(1, function(result){
    // result should be the value of json_num_users
});

Upvotes: 1

Del Pedro
Del Pedro

Reputation: 1213

$.get is running asynchron - it starts a new request to the server, which will return something when all the server side processing is done.

But your paginateUser() function is running inside the browser, it just sends the request (to nowhere/to the server) without waiting for the results.

Upvotes: 0

vittore
vittore

Reputation: 17589

You are not returning anything from paginateUser, if you return result of get, which probably should be $.get you'll have deffered object (after jquery 1.5) which has methods like done then which accept corresponding callbacks as parameters

also you can do this

var p = $.get(....)  ( or $.post or $.ajax etc )

$.when(p).done(mydone).fail(myfail)

function mydone(data){  }
function myfail(err) {  }

EDITED: after your edits I see you are implementing ajax calls on your own, and using jquery for DOM manipulation , which is wierd

better just use $.getJSON method which accepts url and return deffered object , it is much more convineint to use and has solid API

Upvotes: 0

Related Questions