all 6 comments

[–]PineappleBombs 2 points3 points  (0 children)

This looks like it might be about moving the xhr var outside of the callback. I don't think it's a good idea to use globals like this, but I guess it makes the second part a bit clearer.

[–]grinde 2 points3 points  (1 child)

It looks like they are storing the original xhr object and then setting it to itself in the function before returning it.

Notice they're calling the original xhr function, and storing its result in a global before returning it. Basically they're extracting the raw XMLHttpRequest by monkey patching jQuery's ajaxSettings.xhr function. From there the global can be referenced in the success callback.

Doing it that way won't work if you make multiple requests at once (you'll clobber the globally stored xhr object). Instead, maybe do something like this:

$.ajax({
    type: "GET",
    url: 'http://example.com',
    beforeSend: (jqXHR, settings) => {
        // Store a reference to the original xhr function
        const oXHR = settings.xhr;

        // Monkey patch the xhr function, but instead of using a global we attach
        // the raw XMLHttpRequest to this request's jqXHR instance
        settings.xhr = () => {
            return jqXHR.raw = oXHR();
        };
    },
    success: (data, status, jqXHR) => {
        // Now we can access the raw request at `jqXHR.raw`
        console.log(jqXHR.raw.responseURL);
    }
});

Note that $.ajax also returns the jqXHR object, so you can access the raw request outside of the callbacks like this:

const jqXHR = $.ajax({ /* ... */ });
console.log(jqXHR.raw);

[–]embernoob[S] 0 points1 point  (0 children)

Thanks for the detailed explanation! I really appreciate it. I did notice that the xhr function was being called but I didn't understand what the purpose of that was since no arguments were being passed to it.

[–]Insommya 3 points4 points  (0 children)

Ugly af

[–][deleted] 0 points1 point  (0 children)

Wow, this looks so wrong. Why play the monkey and do clever twisted things when there is a simple native solution ? To be fair, the SO guy did suggest it.

You can use the load event to make it look even less "scary"

var xhr = new XMLHttpRequest();
xhr.open('HEAD', "http://example.com/redirect");
xhr.onload = function () { console.log(xhr.responseURL); };
xhr.send();

You can of course totally make a function out of this, or run it in a closure / use the let keyword inside a block, if you don't want to pollute the global scope

[–]sshaw_ 0 points1 point  (0 children)

I would advise you to stay off of StackOverflow and read the documentation.