Search code examples
javascriptjqueryajaxjqxhr

How to return data in jQuery Ajax?


let's say i have a simple function:

    function test(url){
var AjaxCall = $.ajax({
        type: GET,
        url: url,
        data: {},
        success: function(data,status,xhr){
             return xhr
        },
        error: function(xhr,e){
             return xhr
        }
});


    if(xhr.status === 200)console.log('success');


}

So what i want is to treat the errors inside the function not after calling it and adding the callback in the call to treat those error for example, is this possible?


Solution

  • If you are using jQuery lower than 1.8, yes you can by setting async = false

      function test(url){
    var AjaxCall = $.ajax({
            type: GET,
            url: url,
            async : false
            data: {},
            success: function(data,status,xhr){
                 return xhr
            },
            error: function(xhr,e){
                 return xhr
            }
    });
    }
    

    Please note that this is deprecated, and for good reason

    As of jQuery 1.8, the use of async: false with jqXHR ($.Deferred) is deprecated; you must use the success/error/complete callback options instead of the corresponding methods of the jqXHR object such as jqXHR.done() or the deprecated jqXHR.success().

    http://api.jquery.com/jquery.ajax/

    function test(url){
        var AjaxCall = $.ajax({
                type: GET,
                url: url,
                data: {},
                complete: function(xhr, status){
                     if(xhr.status === 200)console.log('success');
                }
        });
    }
    

    And no, you cannot return a value from your function with this method. That's not how asynchronous works. If you want to return, you have to set async = false and that kind of defeats the purpose of using ajax.