How to perform post without reloading the page?

0

How do I make a post for another page without having to go to it, I want to send the data and the return appears on the same page if it worked or not, but I do not know how to do it. I've seen something like this with JavaScript:

$.post

I do not remember the follow-up and I did not find anything that is understood.

    
asked by anonymous 06.12.2017 / 18:15

2 answers

4

This is not a JavaScript function, it is a function that is part of a lib / library for JavaScript that is added manually by you.

This library / lib might be $.post or it might be jQuery (or other compatible) , none of the examples in the other answers will work just add on your page, as it depends on adding jQuery / Zepto to it first.

Using with jQuery / Zepto

If you are going to use jQuery first add it within Zepto (or at the bottom of the page, before <head> ):

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

Ifit'sZeptoaddthis:

<scriptsrc="https://cdnjs.cloudflare.com/ajax/libs/zepto/1.2.0/zepto.min.js"></script>

Then after this tag you can add another tag like this:

  <script src="meujs.js"></script>

And you should create a <body> in the same folder with the following content (it does not have to be exactly like this):

$(function () { //<--- o $(...) equivale a função $.ready(...) que só executa um script quando o DOM (document) tiver sido carregado
      $.post("pagina_que_ira_receber_o_post.php", {
          "variavel1": "valor A",
          "variavel2": "valor B",
          "variavel3": "valor C"
      }).done(function (data) {
          alert(data); //Pega a resposta da pagina_que_ira_receber_o_post.php
      }).fail(function (error) {
          alert(error); //Pega o erro, podendo ser uma exception no parse ou um erro HTTP
      });
});

The page should look like this:

...
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script><scriptsrc="meujs.js"></script>
</head>
<body>
...

Pure JavaScript

You do not need an entire lib to use Ajax (similar to $ .ajax, $ .post, $ .get), you can simply use the native browser API called meujs.js .

Enjoy and read about this:

POST submission example:

var oReq = new XMLHttpRequest();

//Defina como true
oReq.open("POST", "pagina_que_ira_receber_o_post.php", true);

//Função assíncrona que aguarda a resposta
oReq.onreadystatechange = function()
{
    if (oReq.readyState === 4) {
        if (oReq.status >= 200 && oReq.status <= 299) {
            alert(oReq.responseText);// Pega a resposta da pagina_que_ira_receber_o_post.php
        } else {
            alert("Erro HTTP na requisição: " + oReq.status);
        }
    }
};

var variaveis = {
    "variavel1": "valor A",
    "variavel2": "valor B",
    "variavel3": "valor C"
};

var campos = {};

for (var k in variaveis) {
    campos[escape(k)] = escape(variaveis[k]);
}

//Envia a requisição, mas a resposta fica sendo aguardada em Background
oReq.send(campos);
    
06.12.2017 / 18:54
0

In addition to the response from Guilherme , we can also make the request with pure JavaScript through the fetch . It is still an experimental tool yet, but it is already supported in major browsers and has a polyfill if you need support in other browsers.

With fetch , a POST request that sends the data of a form, for example, would be similar to:

const data = new FormData( document.getElementById('form') );
const request = fetch('pagina.php', {method: 'POST', body: data});

request.then(response => {
    if (response.ok) {
        // A requisição foi feita com sucesso...
    } else {
        // Algo de errado não está certo...
    }
});

request.catch(error => {
    // Parece que tem algo errado no 'fetch'...
});

The fetch function basically returns a promise and, if you understand what a promise is, the code is very easy to understand. The first parameter of the function is a URI that identifies the resource on the server, while the second parameter is an object that configures the request, in this case, defining the request method and the data sent by the request body.

If you like semantics, you can leave the code more semantic. In the fetch API itself some classes are defined that help in this part, to mention: Request , Headers and Response . This way, you can set the headers of your request through Headers :

const headers = new Headers({'Origin': '...'});
headers.append('X-Custom-Header', '...');

And the request through class Request :

const request = new Request('pagina.php', {method: 'POST', headers: headers, body: data});

Passing object request to function fetch :

fetch(request).then(response => { ... });

So, when the request is made, the parameter response passed to the callback function will be an instance of class Response .

Read more on % specification for WHATWG .

    
06.12.2017 / 19:09