Is it possible to do Ubmit without refreshing, and without jQuery?

Asked

Viewed 6,898 times

3

My question is this::

  • It is possible to do submit of a form, without having to go to the action of that form?

I mean, I click submit, I am on the same page but the form is validated, without refresh.

How can I do that?

  • Point the action to the same page ?

  • No, for example, I’m on the index.php page, and the action="validate.php", I click Ubmit and continue on the index.php without having to go to.php to validate it.

  • 1

    Yes, it is possible. You must use AJAX.

  • How about we go to validate and put a header('Location: index.php'); or play the content to validate with a include and the action leaves blank or points to you ?

  • Could you give me an example?

  • As is your form, what happens between Submit and the end to validate ?

  • Good is the following, basically what I want is to click Submit, without changing the page and the form to be sent.

  • @Randrade is in doubt, because this one does not ask for jquery.

  • @Bacco I thought about it. However, asks javascript. The other also asks javascript, even if there is no answer

  • Gonçalo, did any of the answers solve your problem?

Show 5 more comments

2 answers

5


To submit the form without refreshing you have to use AJAX and stop the event submit.

Stop the event submit:

var form = document.querySelector('form');
form.addEventListener('submit', function(e){
    e.preventDefault(); // <--- isto pára o envio da form

Merge the data from form

To send via ajax you need to know the url you want to send to. If it’s the same as the form can do

var url = form.action;

If you do not join this string. Then join the data from form:

var formData = new FormData(form);

and everything together with AJAX could be like this:

Send via ajax:

var form = document.querySelector('form');
form.addEventListener('submit', function(e) {
  e.preventDefault(); // <--- isto pára o envio da form

  var url = this.action; // <--- o url que processa a form
  var formData = new FormData(this); // <--- os dados da form
  var ajax = new XMLHttpRequest();
  ajax.open("POST", url, true);
  ajax.onload = function() {
    if (ajax.status == 200) {
      var res = JSON.parse(ajax.responseText); // a resposta do servidor
      // fazer algo com a resposta do servidor
      alert(res);
    } else {
      alert('Algo falhou...');
    }
  };
  ajax.send(formData);
});

Example: http://jsfiddle.net/t65u21xk/

Reading on the MDN: (link)

2

This example is pure javascript, the transaction is being performed through the API Xmlhttprequest and not by action conventional... I mean you wouldn’t even need the tag form with his attributes.

The form:

The issue of onsubmit="return false;", is due to the fact that in the absence of the same, the user will be able to submit the form, typing ENTER or in the case of any type="submit"...

<form  onsubmit="return false;">
    <label>Entrada:</label><input type="text" id="ajaxTextbox" />
    <input type="button" id="ajaxButton" value="Enviar"/><br/>
    <div>Dados Enviados :<div id="envio" style="display: inline-block"></div></div>
</form>

The Ajax:

In this code I am putting the return, to exemplify that the page will not be reloaded, as in your case it is only the sending and not the recovery there you change. However as Ajax is widely used for both shipping and recovery, I’ve already left it that way. For example, the moment a new user goes to register, you can check if the name already exists and ask him to put another one without reloading the page.

In summary Ajax serves both to send and to recover data... Or the 2 as in this case of example...

(
    function()
    {
        var httpRequest;
        document.getElementById("ajaxButton").onclick = function()
        {
            var entrada = document.getElementById("ajaxTextbox").value;
            requisita("validar.php", entrada);
        };
        function requisita(url, entrada)
        {
            httpRequest = new XMLHttpRequest();
            if(!httpRequest)
            {
                alert("Algo está errado verifique a compatibilidade do Navegador !");
                return false;
            }
            httpRequest.onreadystatechange = mostraconteudo;
            httpRequest.open("GET", "validar.php?entrada=" + entrada, true);
            httpRequest.send();
        }
        function mostraconteudo()
        {
            if(httpRequest.readyState === XMLHttpRequest.DONE)
            {
                if(httpRequest.status === 200)
                {
                    document.getElementById("envio").innerHTML = httpRequest.responseText;

                }
                else
                {
                    alert("Algum problema !");
                }
            }
        }
    }
)();

And the validar.php, where you will receive the data... and put your rules.

<?php
$name = $_GET["entrada"];
echo $name; 
if(empty($_GET["entrada"]))
{
    $name = "Não Digitou !";
    echo $name; 
}
?>

I hope I’ve helped... Anything will comment...

  • I’ll edit my question.

  • Ready my doubt, now it is better explained.

  • Ah without giving refresh....

  • Well that’s it, although it was marked as duplicate your question, and the question asks Javascript and not Jquery, maybe now that it is edited and the doubt is clear, I will request that it be reopened if so moderators find useful @bigown

  • The edition you refer to did not change the question, only the term used. Now I edited to make it really different, the "without jQuery" in the title may help ;) I already thought about it yesterday, when I left this comment to @Randrade: http://answall.com/questions/163498/%C3%89-poss%C3%Advel-fazer-Submit-sem-dar-refresh#comment336302_163498

Browser other questions tagged

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