Check if the login exists in jQuery before submitting the form

Asked

Viewed 3,753 times

5

I need to develop a system in which when filling the customer’s registration, is verified if the registered email already exists in the database, and if it already exists, that informs the user (via Ajax) that he already has this registered email, and, otherwise, do the normal sending.

But I don’t want to have to click send first, to know if it exists or not... Is there any way to elaborate this?

2 answers

4


An interesting way to do this is to fill in the field e-mail you use the method change jQuery to send an Ajax.

In PHP he will make a select checking whether this email exists in the database, and if it exists, you can show a message that the email already exists in the success ajax.

Example:

var email = $("#email");
email.change(function() {
  $.ajax({
    url: 'teste.php',
    type: 'POST',
    data: email.val(),
    dataType: 'json',
    success: function(data) {
      console.log(data);
      if (data.email) { // se existir
        $("#resposta").append('Ja existe um usuario cadastrado com este email');
      }

    },
    error: function() {
      $("#resultado").show().fadeOut(5000);
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type='text' id='email'>
<div id='resposta'></div>

In php do a test just returning true to see if the return of ajax is working, after that you can do the select and put the proper return:

   $output = true;
   echo json_encode($output);
  • I think that would be enough, would you have a practical example of this? Or at least a similar solution? Grateful!

  • I use the Codeigniter

  • It didn’t work... Points error in jQuery

  • @Andrébaill in php you just need to select and resume if there is an email I believe it is not difficult to modify the code to perform this in codeigniter, as for the error in jquery which would it be ?

  • @gustavox did you have any idea what might be going on? I couldn’t even elaborate.

  • it returns nothing... As much as I search only on the variable, without entering mysql... does not return...

  • Could you elaborate another example? In this one I couldn’t.. From PHP I can elaborate the mysql questions, I just don’t understand anything from jquery.. @gabrielrodrigues

  • I’m sorry @Andrébaill, I just edited to correct some small inaccuracies of the text... but look, it doesn’t return any errors? This kind of situation is complicated to help, because by relying on external file (PHP and Json) it is difficult to create a verifiable example (for those who try to help can go testing)... but just for the record, you said that it does not return anything, but the page stops running? Because if you get an infinite loop, it could be a PHP error.

  • Yes, normal... But the result does not come, and I entered the console and points jQuery error.

  • 2

    @Andrébaill edited the answer making it simpler, do a test, here it works.

  • I answered the question differently: http://answall.com/questions/76686/verifi-se-o-email-filled-j%C3%A1-exists-in-database-without-refresh

Show 6 more comments

1

I know it’s been a long time this post, but here’s something that might help you, you could simulate sending the form with a div or button styled as Submit button, follow the idea below:

$(document).ready(function(){
  
  $('#bs-em .button').on('click', function(){
    var email = $('#email').val();


    //Envia o valor de email através do método POST para a página verify 
//para verificar se o email já existe, caso exista ele retorna falso 
//através do parâmetro 'e' da função, se não existe ele retorna true, 
//aí é só comparar esses valores, e caso seja true, você usa o método submit()
 //para poder submeter o formulário a página insert.php. Você também pode usar $.ajax.


    $.post('configs/verify.php', {email: email}, function(e){
      //Então você faz uma comparação de valores, entre false e true
      if(e == false){
        alert("Desculpe, o email informado já existe.");
      }else{
        $('#bs-em').submit();
      }
    });
  });
});

//O código JQuery está um pouco genérico, pq estou fazendo diretamente 
//pelo pt.stackoverflow, então não pude testar o código ainda, caso der algum erro, 
//me avisa, provavelmente pode dar em duas coisas, ou na forma que fiz a comparação 
//do parâmetro 'e', ou então o if dentro da função $.post, por isso eu queria testar, 
//mas qualquer coisa me avisem, a ideia é mais ou menos essa, verificar se existe 
//antes de submeter o formulário
*{
  margin: 0;
  padding: 0;
}
body{
  background-color: #333;
}
form{
  position: absolute;
  top: 0;
  bottom: 0;
  right: 0;
  left: 0;
  margin: auto;
  width: 300px;
  height: 100px;
  background-color: #dcdcdc;
  padding: 8px;
  box-shadow: 2px 2px 6px 0;
}
form input[type=text]{
  border: 0;
  width: 284px;
  height: 30px;
  font-family: arial, sans-serif;
  font-size: 14px;
  padding: 7px;
}
form .button{
  width: 130px;
  height: 35px;
  background-color: #45349d;
  display: flex;
  align-items: center;
  justify-content: center;
  font-family: arial, sans-serif;
  font-size: 14px;
  color: #fff;
  cursor: pointer;
  margin-top: 7px;
  box-shadow: 2px 2px 4px 1px #222;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>

<form action="insert.php" method="post" id="bs-em">
  <input type="text" name="email" class="email" id="email" placeholder="Inserir E-mail aqui" />
  <div class="button">ENVIAR</div>
</form>

I hope I helped you guys! Thanks

Browser other questions tagged

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