Send ajax requests using pure javascript POST method

Asked

Viewed 3,799 times

1

I am trying to submit a form using AJAX through the POST method but I am not succeeding. Can someone help me?

function gooSubmit(url,id){
    //declaração das variáveis
    var sd  = document.getElementById(id);
    var req = rq();
    //exibi a imagem de progresso
    sd.innerHTML = "<img id=\"preload\" src=\"assets/img/preload.gif\" alt=\"Preload\" />";
    setTimeout(function(){
        //iniciar uma requisição
        req.open("POST", url, true);
        //atribui uma função para ser executada sempre que houver uma mudança de estado
        req.onreadystatechange = function(){
            //verifica se foi concluído com sucesso e a conexão é fechada (readyState=4)
            if (req.readyState == 4){
                //verifica se o arquivo foi encontrado com sucesso
                if (req.status == 200){
                    sd.innerHTML = req.responseText;
                    tinymce_init();//inicia o bbcode
                    en();//faz a entrada
                }else{
                    //caso ocorra algum erro exibe a mensagem de erro com o status do servidor
                    sd.innerHTML = "Erro: " + req.statusText;
                }
            }
        };
        req.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
        req.send();
    },100);
}

Note rq() is a polyfill for ajax:

function rq() {
    try {
        request = new XMLHttpRequest();
    } catch (IEAtual) {
        try {
            request = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (IEAntigo) {
            try {
                request = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (falha) {
                request = false;
            }
        }
    }
    if (!request) alert("Seu Navegador não suporta Ajax!");
    else return request
}

1 answer

1


To send data via ajax with POST you have to take these steps:

  • fetch the data from the forms
  • prepare them in a string or Formdata query
  • send in the method .send() ajax

An example I use a lot is like this:

var ajax = (function() {
    function prepareData(data) {
        if (typeof data == 'string') return data;
        var pairs = Object.keys(data).map(function(key) {
            return [key, data[key]].map(encodeURIComponent).join('=');
        }).join('&');

        return pairs;
    }
    return function(_data, cb) {
        var data = prepareData(_data);
        var request = new XMLHttpRequest();
        request.open('POST', '/urlParaOServidor', true);
        request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
        request.onload = function() {
            if (request.status >= 200 && request.status < 400) cb(request.responseText);
            else console.log(1, 'Houve um erro :(');
        };
        request.onerror = function() {
            console.log(2, 'Houve um erro :(');
        };
        request.send(data);
    }
})();

The prepare data function transforms simple objects into a query string, for example {a: 19, b: 24} would be a=19&b=24 and so ajax knows what to send.

Thus, taking for example:

<form>
    <input type="text" name="nome">
    <input type="text" name="idade">
</form>

You can do so (simple example):

var data = {
    nome: document.querySelector(input[name="nome"]).value,
    idade: document.querySelector(input[name="idade"]).value
};

ajax(data, function(res){
    console.log('O servidor respondeu com:', res);
});

There are more effective ways to get data, but it’s simple as an example.

Browser other questions tagged

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