Jquery - include variables in ajax

Asked

Viewed 114 times

0

Before you ask 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 make check.php read the values of email and password. I did some research and it can be done by Data, as I can do?

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:

  • jQuery.ajax (to perform AJAX requests);
  • .val() (to obtain the value of an element).

0

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

Please note that there are some typos in your form:

</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 the .serialize():

var dados = form.serialize();

The variable dados values of form fields, for example:

[email protected]&senha=senha_digitada

Applying in the 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'];
?> 

Browser other questions tagged

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