AJAX request with pure Javascript (no Apis)

Asked

Viewed 24,456 times

66

Usually, when we need to resort to requisitions AJAX using Javascript, we have handy Apis that help us with this (e.g.: jQuery).

However, what would be the safest and cross-browser to make these requests (POST and GET) using Pure Javascript?

  • 4

    Note: I moved the cross-Omain support part to another question: http://answall.com/questions/3183/requisicao-ajax-cross-domain-com-javascript-puro-apis

  • I used it before I discovered jquery. After this wonder came, fortunately, we no longer need to worry about this cross-browser issue, the code gets cleaner. Who evolves jquery that will worry about it. I recommend using ajax with jquery.

5 answers

53

The site quirksmode.org has a complete example Ajax request designed to work on most browsers (current and old), without the use of external libraries:

function sendRequest(url,callback,postData) {
    var req = createXMLHTTPObject();
    if (!req) return;
    var method = (postData) ? "POST" : "GET";
    req.open(method,url,true);
    req.setRequestHeader('User-Agent','XMLHTTP/1.0');
    if (postData)
        req.setRequestHeader('Content-type','application/x-www-form-urlencoded');
    req.onreadystatechange = function () {
        if (req.readyState != 4) return;
        if (req.status != 200 && req.status != 304) {
//          alert('HTTP error ' + req.status);
            return;
        }
        callback(req);
    }
    if (req.readyState == 4) return;
    req.send(postData);
}

var XMLHttpFactories = [
    function () {return new XMLHttpRequest()},
    function () {return new ActiveXObject("Msxml2.XMLHTTP")},
    function () {return new ActiveXObject("Msxml3.XMLHTTP")},
    function () {return new ActiveXObject("Microsoft.XMLHTTP")}
];

function createXMLHTTPObject() {
    var xmlhttp = false;
    for (var i=0;i<XMLHttpFactories.length;i++) {
        try {
            xmlhttp = XMLHttpFactories[i]();
        }
        catch (e) {
            continue;
        }
        break;
    }
    return xmlhttp;
}

The "standardized" part (i.e. supported by recent browsers, which follow the established standards) is the one that involves the XMLHttpRequest. The rest are there to support old browsers.

Source: that answer in the SOEN

  • +1 What about the cross-Omain request case? This approach would cross-browser support?

  • 6

    @Evertonagner I think the cross-Omain question deserves a question itself. It’s much more complicated. You have several options: CORS, JSONP, proxy

  • 2

    @Evertonagner That’s what Juan Mendes said. In some of these solutions (e.g., CORS) there is no need to move anything in the code, it works the same way for the same domain and for external domains; what has to be changed is the configuration of the server (indicating that it accepts Ajax for other domains). Others (e.g., JSONP) need their own code for this. That is, subject for another question...

  • Done! http://answall.com/questions/3183/requisicao-ajax-cross-domain-com-javascript-puro-sem-apis

15


With the new browser Apis instead of using XMLHttpRequest, we can use the API fetch to perform asynchronous HTTP requests.

The use of fetch is much simpler compared to its predecessor. In addition, the API in question uses Promises, which is significantly interesting, given that we can use async/await if we wish.

To demonstrate how it works, let’s access the Github API:

const baseurl = 'https://api.github.com/users'
const username = 'lffg'

fetch(`${baseurl}/${username}`)
  .then((body) => body.json())
  .then((data) => {
    console.log(`O usuário ${data.login} tem ${data.public_repos} repositórios públicos.`)
  })
  .catch((error) => console.error('Whoops! Erro:', error.message || error))

It is also possible to notice in row 5 of the previous example that the API fetch also provides ways to transform the response (Body) of the JSON request (Body.json), text (Body.text) and several others which you can consult here.

For the various types that can be passed to the body of the HTTP request, read What are the main types accepted by the Fetch API for the HTTP request body?.

Compatibility between browsers ancient

The API fetch is already relatively well supported. See the compatibility table.

If you want to support some version or browser that does not yet support it, you can use a polyfill. You can find several, such as this.

  • Very good update! Actually it is currently the most recommended way

14

try
{
    var loader = new XMLHttpRequest();
}
catch (err)
{
    // versões antigas do Internet Explorer não tem a classe XMLHttpRequest, precisa usar esse componente ActiveX
    var loader = new ActiveXObject('Microsoft.XMLHTTP');
}

loader.onreadystatechange = function ()
{
    // esse callback é chamado várias vezes para cada mudança de readyState
    // readyState 4 é chamado quando o request é concluído (mesmo que .done() do jQuery)
    // você também pode checar o this.status para ver código de retorno HTTP
    // 200 é sucesso
    // 404 é página não encontrada
    // 403 é acesso negado
    // 500 é erro interno do servidor etc
    if (this.readyState == 4)
    {
        alert(this.responseText);
    }
}
loader.open('POST', 'http://www.exemple.com/submit.php', true);
loader.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
loader.send('nome=Manoel&idade=50'); // use null para métodos que não forem POST

10

The pure Javascript AJAX request is made with the object XMLHttpRequest. Unless you want to use an older version of Internet Explorer, for example, that used an object ActiveX. So, one usually starts with this "quickfix":

var xmlhttp;
if (window.XMLHttpRequest) xmlhttp = new XMLHttpRequest();
else if(window.ActiveXObject) xmlhttp = new ActiveXObject("MSXML2.XMLHTTP.3.0");
else throw "AJAX não suportado!";

Then you need to listen to the event onreadystatechange of your Xmlhttprequest object:

xmlhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) { // Download concluído e a resposta não contém erros
        return this.responseText; // this dentro dessa function é seu XMLHttpRequest
    }
    // Você pode colocar outras condições aqui, como responder com erro quando o status for 404 ou 500, por exemplo
}

And finally start the request:

xmlhttp.open(metodo, url, true);
// metodo: "GET", "POST", "PUT", "DELETE"... enfim, um suportado pelo HTTP
// url: a URL do seu request
// o terceiro argumento é o 'A' do AJAX. True = request assíncrono; False = request síncrono.
loader.send(queryString); // quesyString é opcional

7

Follow the example below:

try{
    xmlhttp = new XMLHttpRequest();
}catch(ee){
    try{
        xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
    }catch(e){
        try{
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }catch(E){
            xmlhttp = false;
        }
    }
}

function pegarCep( CEP ){
    if( CEP.length==0) return false;
    var divCep = document.getElementById('divCep');
    divCep.innerHTML = "Carregando...";
    xmlhttp.open("GET", "/cadastro-sms/br/cep.asp?CEP="+ CEP,true);
    xmlhttp.onreadystatechange=function() {
        if (xmlhttp.readyState==4){
            var resposta = xmlhttp.responseText;
            divCep.innerHTML = resposta;
        }
    }
    xmlhttp.send(null);             
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.