0

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?

Abude
  • 2,112
  • 7
  • 35
  • 58
  • I think you do so, if I understood right, in the array you're passing there; pass a anonymous function in error and success (as you're doing) and handle everything you want there –  Mar 27 '15 at 06:50
  • yes but in the success if i do `return xhr` and then when calling function to do `var x = test(url); console.log(x);` to have the results; – Abude Mar 27 '15 at 06:53
  • why not just move the if statement into the success callback? – Will Reese Mar 27 '15 at 06:59
  • Are you after synchronous communication? If so, could you explain why? – Matijs Mar 27 '15 at 06:59

1 Answers1

1

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.

Quannt
  • 2,035
  • 2
  • 21
  • 29
  • yep, i did know that, but is there another solution? – Abude Mar 27 '15 at 06:52
  • yes, the solution is there "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()." – Quannt Mar 27 '15 at 06:53
  • can you give a snippet for those please ? – Abude Mar 27 '15 at 06:53
  • http://stackoverflow.com/questions/14220321/how-to-return-the-response-from-an-asynchronous-call – Vinod Mar 27 '15 at 07:01