jQuery check php database field

Asked

Viewed 614 times

1

I have the following button:

<button type="submit" class="btn btn-info pull-right"><? echo $titulo; ?></button>

This button sends a form action, with the completed data.

And I also have the following field:

<input type="text" class="form-control" name="con_email" id="con_email" placeholder="E-mail da Consultora" value="<? if(isset($dados->con_email)){ echo $dados->con_email; } ?>" required>

I need you to press the Ubmit button and run a check to see if this e-mail already exists in the database. I know it is possible to elaborate this in jQuery, but I don’t know where to start the check.

I thought only when sending, I do the search via php and return true or false, returning, true, I just call a modal, returning false, call the ajax to Insert in the database, using the get method or post.

Does anyone have any idea how I can craft this jQuery?

  • Your logic is right, now is implementation detail, depends on the way you usually do, in short it will be a request to validate the email and another to send the form. and the form depends on the email.

  • Exactly, but I think about validating, if it comes true (1), I print the message if not I do the inclusion, via jquery itself.. php I work it, as needed, what I don’t know how to develop would be this jquery. :)

  • I make everything work first without jquery/Ajax, with all the necessary validations on the server side, then I make Ajax send the original form and handle the return, the end result is that everything works exactly the same even if it is without js.

3 answers

3


I imagine your html is like this or something:

<form action="gravar.php" method="post" id="formGravar">

    <input type="text" class="form-control" name="con_email" id="con_email" placeholder="E-mail da Consultora" value="<? if(isset($dados->con_email)){ echo $dados->con_email; } ?>" required>
    <button type="button" id="btnCheck" class="btn btn-info pull-right"><? echo $titulo; ?></button>

</form>

Javascript you can do so:

<script>
$("#btnCheck").on('click', function(){
    $.post('checar_email.php', {email: $("#con_email").val()}, function(r){
        if(r == '0'){
            $("#formGravar").submit();
        }else{
            alert('e-mail já existe na base');
        }
    });
});
</script>

Javascript will act on the button without working with the form initially. It will send an ajax to PHP "checar_email.php" where you should receive the $_POST['email'] and check the base whether or not the e-mail has been typed. If you have it you return "1" and show an Alert and if not "0" will give a Submit in the form you send to "save.php" which will insert the email in the base.

"checar_email.php" file looks something like this:

<?php
$email = $_POST['email'];

//Aqui é uma função que irá se conectar a base e verificar se existe o e-mail ou não. 
//Você pode substituir isso pelo seu método de validação
$check = checarEmail($email);

if($check){
    echo '1';
}else{
    echo '0';
}
?>

It is worth remembering that the above example is very basic and has no kind of security. I recommend you work on the security of the data coming from the form to avoid SQL injections and also work on the handling of errors.

I hope I’ve helped.

Good luck!

  • I think that would be this, I will test here to see... but since it is an internal system, already with login validation, Sesssions and also module permissions, I think I will not have major problems. I appreciate your help, post news in a little while.

  • Hello, this jQuery didn’t even arrive at the validation... It goes right through.

  • You say q when clicking the button does not check? The button has q be type="button" otherwise the save form is sent along with the ajax.

  • Guys, and I thought the person was using Codeigniter...

0

Good morning. I’m having problems with the Jquery code posted by Shutupmagda. I continue the POST or create a new POST with my codes (controller, model, view and jquery )?

0

You just need a method controlling this request (safely). Try it like this:

CONTROLLER:

function check_email() {
  $this->load->library('form_validation');
  $this->form_validation->set_rules('email','trim|required|valid_email');
  if ($this->form_validation->run() === FALSE) {
    show_error('Dados inválidos!');
  }
  else{
    echo json_encode($this->nome_model->check_email());
 }
}

MODEL:

function check_email(){
    $email = $this->db->escape_str($this->input->post('email'));
    $this->db->where('email',$email);
    $query = $this->db->get(self::TABELA);
    if(!empty($query->result_array())){
        return TRUE;
    }
    return FALSE;
}

Jquery:

$('#id_do_botao').click(function(){
 $.post("nome_do_controller/check_email", {
 email: $('#con_email').val()
},
 function (resp) {
  var response = jQuery.parseJSON(resp);
  if(response === 'true'){
   $('#id_do_modal').modal('show');
  }
 });
}

Basically: the onclick event of the button calls the method 'check_email()' of the controller via POST passing the value of the field 'con_email'; The controller answers 'true' or 'false' based on the method 'check_mail()' of the model; Jquery uses the answer to show or not to show your modal.

Browser other questions tagged

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