Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript ajax request without framework

Does anyone know how to make ajax request function that works cross-browser WITHOUT using a javascript framework like jQuery, etc.?

like image 383
Rizky Ramadhan Avatar asked May 06 '11 06:05

Rizky Ramadhan


People also ask

Can AJAX work without JavaScript?

AJAX isn't possible without Javascript, because it presupposes JS code running on the client. If JS is disabled, there's nothing that can execute in the browser and contact the server - only "dead" HTML and CSS.

Is AJAX a framework or library?

An Ajax framework is a cross-browser framework or library that assists developers in the creation of rich internet applications, that use Ajax.

What is the difference between AJAX request and HTTP request?

AJAX stands for asynchronous javascript and XML so if you are using javascript to load data after the browser request has finished you are doing AJAX. REST on the other hand stands for Representational State Transfer which as Stefan Billet pointed out uses HTTP requests to transfer data.


1 Answers

The XMLHttpRequest object isn't actually all that complicated to use. To be broadly compatible, you have to play a bit of a game to create the object, but after that it's fairly straightforward for simple operations.

Microsoft has examples on the MSDN page for XMLHttpRequest, including a function for creating the object in a cross-browser way that supports early versions of IE. Here's their example:

function getXMLHttpRequest() 
{
    if (window.XMLHttpRequest) {
        return new window.XMLHttpRequest;
    }
    else {
        try {
            return new ActiveXObject("MSXML2.XMLHTTP.3.0");
        }
        catch(ex) {
            return null;
        }
    }
}

function handler()
{
    if (oReq.readyState == 4 /* complete */) {
        if (oReq.status == 200) {
            alert(oReq.responseText);
        }
    }
}

var oReq = getXMLHttpRequest();

if (oReq != null) {
    oReq.open("GET", "http://localhost/test.xml", true);
    oReq.onreadystatechange = handler;
    oReq.send();
}
else {
    window.alert("AJAX (XMLHTTP) not supported.");
}

I'm not suggesting the above exemplifies best practices (Microsoft seems to have their MSDN examples largely written by very, very inexperienced engineers), but it gives you a starting point. For instance, the above requires that the response status be 200 for success, where of course the HTTP specification is clear that anything the 200 <= n <= 299 range is "success".

like image 94
T.J. Crowder Avatar answered Oct 23 '22 08:10

T.J. Crowder