Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery $.ajax() functionality - Accessing the XMLHttpRequest object

Tags:

jquery

Is it possible to access the XMLHttpRequest object from the success callback of the $.ajax() function? Specifically I need access to XMLHttpRequest.responseBody in IE. Per the documentation the returned jqXHR object does not expose the .responseBody property.

This seems to be a minor oversite that has a huge impact when dealing with binary data. If the .responseBody property or the underlying XMLHttpRequest object is not accessible I'll have to skip jQuery for ajax and code it in, shudder, pure javascript.

Update

I am infact looking for the responceBody variable, not the responceText variable that is readily accessible from within $.ajax()

like image 398
Justin808 Avatar asked Jun 01 '11 06:06

Justin808


People also ask

How is the XMLHttpRequest object used in AJAX?

The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

What is the major difference between jQuery AJAX and XMLHttpRequest XHR )?

XMLHttpRequest is the raw browser object that jQuery wraps into a more usable and simplified form and cross browser consistent functionality. jQuery. ajax is a general Ajax requester in jQuery that can do any type and content requests.


2 Answers

Provide the xhr settings field to create the XMLHttpRequest, and retain a reference to the object. A quick way to do this is by adding it to the settings object (which is accessible via this in the callbacks).

$.ajax({
    url: "/whatever",
    xhr: function(){
        return this._xhr = new XMLHttpRequest();
    },
    success: function(){
        console.log("Original XHR:", this._xhr);
    }
});
like image 75
Glenn Lane Avatar answered Oct 11 '22 13:10

Glenn Lane


You can use beforeSend callback too:

$.ajax({
    beforeSend: function(jqXHR, settings){
        // Here you are the XHR object
        console.log(settings.xhr());
    }
});
like image 22
Manuel Bitto Avatar answered Oct 11 '22 14:10

Manuel Bitto