How to post without reloading the page?

Asked

Viewed 723 times

0

As I do to perform a post to another page without having to go to it, I want to send the data and appear the return on the same page whether it worked or not sending, but I do not know how to do. I’ve seen something like this with Javascript:

$.post

But then I can’t remember the follow-up and I couldn’t find anything.

2 answers

4


This $.post nay is a Javascript function, is a function that is part of a lib/library for Javascript that is added manually by you.

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


Using with jQuery/Zepto

If you’re going to use jQuery first add this inside <head> (or at the end of the page, before the <body>):

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

If it’s Zepto add this:

 <script src="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 in the same folder a meujs.js with the following content (it doesn’t 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>
<script src="meujs.js"></script>
</head>
<body>
...

Pure Javascript

You nay need an entire lib (library) to use Ajax (similar to $.ajax, $.post, $.get), you can simply use the native browser API called XmlHttpRequest.

Take a look at this:

Example of sending POST:

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);
  • 1

    Since you did not advertise let me do for you : "You can also use the Lib Pjax and leave your dynamic page with no need to reload everything again"

  • It’s a great lib expose her :D

  • @Guilhermelautert kkkkk, is almost coming out version 0.6.0, which I intend to be "more practical" :) - I will post on that question about Pjax himself, but thanks for remembering, I need to be less humble and start making more jabas hehe

0

In addition to the William, we can also request with pure Javascript through the API fetch. At the moment, it is still an experimental tool, but already has support in the main browsers and has a polyfill if you need support in other browsers.

With the fetch, a POST request that sends the data of a form, for example, would look 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 function fetch 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 body of the same.

If you like semantics, you can make the code more semantic. In the API itself fetch are defined some classes that help in this part, to quote: 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 the class Request:

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

Passing the object request for the function fetch:

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

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

Read more on specification of fetch on WHATWG.

Browser other questions tagged

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