How to get the form data without using Submit?

Asked

Viewed 164 times

-1

So I have a question here. I needed to take the data related to a form and send to my Ajax automatically (in a structured way), without pressing any Ubmit button or using an onClick function.

I built my code like this

<form id="ladologin">
    <input id="acesso" name="acesso" value="#acesso">
    <input id="senha" name="senha" value="senha">

    <script>
        var form = document.getElementById("ladologin"); 
        var formData = new FormData(form);

        console.log(form):
        //console.log(formData):
    </script>
</form>

my console returns an error while trying to recover the form data

Uncaught SyntaxError: Unexpected token :?token=R1H7-9X-GAZ3:11 Uncaught SyntaxError: Unexpected token :

Does anyone have any idea how to solve?

  • "keyup" or "keydown" functions can help you with this

2 answers

0

If it’s just to fix your error at the end of your console.log you have one : instead of ;

To send the data on you can try as Walter said up there.

0

I imagine you think about implementing something that when you finish typing and press a key, example: "Enter" you want it to send the data to the HTTP server without the need for a Ubmit button, right?

Following this line I believe you can do something like this:


//Escuta o evento de pressionar alguma tecla
document.addEventListener('keydown', (event) => {
  //Caso a tecla seja o enter (codigo 13)
  if(event.keyCode == 13) {
     //Valida se algo foi preenchido
     if(dadosPreenchidos()) {
         //Chama a função que envia o formulário
         enviarFormulario();  
     } else {
         alert('Acesso e senha devem ser preenchidos');
     }

  }
});

function dadosPreenchidos() {
   var acesso = document.getElementById('acesso').value;
   var senha = document.getElementById('senha').value;
   return acesso !== "" && senha !== "";
}

function enviarFormulario() {
  var xhttp = new XMLHttpRequest();
  //Após modificar o estado da requisição vc verifica se o servidor respondeu 200 (sucesso) e faz alguma ação
  xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
      alert('Formulario enviado com sucesso');
    }
  };
  //Monta o request com o conteudo preenchido no seu formulario
  var data = new FormData();
  var acesso = document.getElementById('acesso').value;
  var senha = document.getElementById('senha').value;
  data.append('acesso', 'person');
  data.append('senha', 'password');
  //Coloque o caminho do seu servidor / recurso / rota que recebe os dados por POST
  xhttp.open("POST", "sua-rota-http-post", true);
  //Envia os dados
  xhttp.send(data);
}

Browser other questions tagged

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