Question

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?
};
Was it helpful?

Solution

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

OTHER TIPS

I believe the simplest way would be:

this.url

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

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);
    }
});

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top