jqueryajaxgetjqxhr

Ajax GET url on error jqxhr


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

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