Search code examples
jqueryjquery-eventsevent-loop

alert-ing return value of ajax call


(1. Do you find it useful to have a global jQuery ajax 'helper' that you can call ajax(url,data,async) ? )

function ajax(ajax_url, ajax_data, ajax_async){
  ajax_async = typeof(ajax_async) != 'undefined' ? ajax_async : true;

  $.ajax({
    type: 'GET',
    url: ajax_url,
    data: ajax_data,
    async: ajax_async,
    dataType: 'text',
    success: function(response) {
        return response;
    },
    error: function(){

    }
  });
}

If I'm calling a function that places a GET and returns the success response.

alert(ajax('localhost/hello','',false);

If I do alert(get_ajax()) I get an alert of 'undefined'.. even if there was a return value

I see its an event loop issue, but I async:false in the ajax call. thoughts?


Solution

  • This is one of those questions that has been asked a million times, but it's nearly impossible to search. Anyway, the problem is that when you return from here...

    success: function(response) {
        return response;
    }
    

    ...you're not returning from the ajax() function but the anonymous success function. To return the value from the main function you have to save the string to a variable so that you can return from the correct function.

    var val = '';
    
    $.ajax({
        //       ....
        success: function(response) {
           val = response;
        },
        //       ....
    });
    
    return val;
    

    Note that this only works when you're making a synchronous call. For asynchronous calls it's better to give a callback function as an argument and use it as the success function.