Sheraz Ali
Sheraz Ali

Reputation: 315

Ajax Method without XMLHttpRequest() Object

I have one query about Ajax methodology. I am used to work with ajax like i use four simple lines written below:

$.ajax({
            type: "POST",
            url: "/application/group/addMembers",
            data: {memberIds: selectedMembers, groupId:<?php echo $this->groupId; ?>},
            success: (function(msg) {
              // alert(msg);
                var ans = JSON.parse(msg);
                alert(ans['message']); // msg is array returned from php script in json
            })
        });

Now, When i study more on different sites or tutorials. They do ajax by creating XMLHTMLREQUEST(), which is used to exchange information with server. And some more things like open, send functions.

But i don't create XMLHTMLREQUEST object and my ajax still works fine. I just want to know the difference. Do i lose something when i don't communicate with server using XMLHTMLREQUEST object. I did search on it. But i still need an answer.

Upvotes: 2

Views: 1024

Answers (2)

Ahmad Anas
Ahmad Anas

Reputation: 113

the difference between your four simple line and XMLHttpRequest() is the language itself where XMLHttpRequest() is pure javascript while your code above is jquery. infact you could ignore both and use jQuery.get() & jQuery.load() as they are higher-level alternatives and easier to use. If less common options are required, though, $.ajax() can be used more flexibly.

Upvotes: 1

Ethan
Ethan

Reputation: 2784

Different browsers implement AJAX differently (Actually only IE really). jQuery handles all of the cross-browser implementation differences and creates the XHR object in the background.

From jQuery Source code:

jQuery.ajaxSettings.xhr = function() {
    try {
        return new XMLHttpRequest();
    } catch( e ) {}
};

var xhrSupported = jQuery.ajaxSettings.xhr(),
    xhrSuccessStatus = {
        // file protocol always yields status code 0, assume 200
        0: 200,
        // Support: IE9
        // #1450: sometimes IE returns 1223 when it should be 204
        1223: 204
    },
    // Support: IE9
    // We need to keep track of outbound xhr and abort them manually
    // because IE is not smart enough to do it all by itself
    xhrId = 0,
    xhrCallbacks = {};

if ( window.ActiveXObject ) {
    jQuery( window ).on( "unload", function() {
        for( var key in xhrCallbacks ) {
            xhrCallbacks[ key ]();
        }
        xhrCallbacks = undefined;
    });
}

jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported );
jQuery.support.ajax = xhrSupported = !!xhrSupported;

Upvotes: 0

Related Questions