Jquery - include variables in ajax

0

Before asking, I'll leave my script:

Html

</form>
  <input type="text" id="email">
  <input type="password id="senha">
  <button>Entrar</button>
</form>

Jquery

 var form = $('form');
 var email = $('#email');
 var senha = $('#senha');

    form.submit(function(event)({
      event.preventDefault();
      $.ajax({
        url: 'verificar.php',
      )}
    )}

How can I have verify.php read the values of email and password . I have researched and can be done by Data, how can I do?

    
asked by anonymous 08.04.2018 / 20:48

2 answers

0

You can modify your script for this:

$('form').on('submit', function(event) {
  event.preventDefault();

  var email = $('#email').val();
  var senha = $('#senha').val();

  $.ajax({
    url: 'verificar.php',
    type: 'POST', /** Altere para  'GET' se o método de requisição for GET. */
    data: {
      email: email,
      senha: senha
    }
  });
});

Note: I suggest you read the jQuery API for the following methods:

08.04.2018 / 21:07
0

Instead of using id s in form fields, you can use name and use the method .serialize() , which will return all fields in a string to be sent by Ajax to the PHP page.

Note that your form there are some typos:

</form> <- aqui o form foi fechado em vez de ser aberto
  <input type="text" id="email">
  <input type="password id="senha"> <- aqui faltou aspas para fechar o type
  <button>Entrar</button>
</form>

Using name and correcting the above errors, your form would look like this:

<form>
  <input type="text" name="email">
  <input type="password" name="senha">
  <button>Entrar</button>
</form>

Using .serialize() :

var dados = form.serialize();

The variable dados becomes the values of the form fields, for example:

[email protected]&senha=senha_digitada

Applying in submit and Ajax with the POST method:

var form = $('form');

form.submit(function(event){
   event.preventDefault();

   var dados = form.serialize();

   $.ajax({
      type: 'POST',
      data: dados,
      url: 'verificar.php',
      success: function(data){
         // faça alguma coisa se o Ajax foi bem sucedido;
      }
   });
});

In the PHP file verificar.php , you capture the values with:

<?php
$email = $_POST['email'];
$senha = $_POST['senha'];
?> 
    
09.04.2018 / 00:47