Ajax GET url on error jqxhr

22.5k views Asked by At

I have an ajax request which I am deliberately failing from my server side code to trigger the error handling event. I was wondering if it was possible here to get the URL it attempted? I want to grab that URL and inject it into a hyper link and retry the request.

Is this possible?

EDIT I am able to see the attempted URL request being made via FireBug and inspected the jqxhr object via console.dir() and can't seem to find anything which helps me identify the URL it attempted to call. Ideally, don't want to store a global variable was hoping to get this from the arguments.

Thanks in advance, O.

$.ajax({
    type: 'get',
    url: 'somewhere/foo',
    context: this,
    success: this.mySuccess,
    error: this.myError,
    cache: false
});

myError = function (jqXhr, textStatus) {
    alert(jqXhr.url); //Get url of failed request and inject it into hyper link?
};
4

There are 4 answers

4
Khawer Zeshan On BEST ANSWER

Save your url in a variable. And you can use it in the error function. Obviously the url will be same as it was supplied in the url parameter of the ajax request

var url = 'somewhere/foo';

$.ajax({
    type: 'get',
    url: url,
    context: this,
    success: this.mySuccess,
    error: this.myError,
    cache: false,
    error: function(jqXHR, exception) {
       //use url variable here   
    }
});

Another option can be this

$.ajax({
    type: 'get',
    url: 'https://google.com',
    context: this,
    success: this.mySuccess,
    error: this.myError,
    cache: false,
    beforeSend: function(jqXHR, settings) {
        jqXHR.url = settings.url;
    },
    error: function(jqXHR, exception) {
        alert(jqXHR.url);
    }
});

FIDDLE

3
neves On

I believe the simplest way would be:

this.url

The this should be bounded to the ajax settings object that has the url attribute.

2
jcubic On

Adding to @KhawerZeshan answer. It's better to set beforeAjax globally:

$.ajaxSetup({
    beforeSend: function(jqXHR, settings) {
        jqXHR.url = settings.url;
    }
});

This way if you use it with async await:

try {
   await $.get('http://example.com');
} catch(e) {
   console.log(e.url);
}
0
Honkalonkalooooohhh On

The easiest would be to just access the url via the ajax settings (JQueryAjaxSettings) object of the error callbacks context.

$.ajax({
    type: 'get',   
    url: 'somewhere/foo',    
    error: function() {
        alert(this.url);
    }
});