highcal highcal - 4 years ago 178
PHP Question

check if email exist in database SQL using codeigniter and AJAX

modal screenshot

i have a form inside bootstrap modal, i want to validate if the email already exist in database. the result direct to the blank page with this thing '{"valid":false,"msg":"Email is already taken"}'. i want the msg appear just like i figure it in screenshot.

View

<?php echo form_open('KulinerControl/isEmailExist', 'id="myform"'); ?>
<div id="msg"> </div>
<input type="text" name="email" id="email" class="input-lg formcontrol">
<button type="submit">Submit</button>
</form>


JS

$(document).ready(function(){
$('#myform').on('submit', function(e) {
var email = $('#email').val();
$.ajax({
type: "POST",
url: "<?php echo base_url()?>KulinerControl/isEmailExist",
dataType: "json",
data: "email="+email,
success: function(data){
if(data.valid){
$('#msg').html(data.msg);
}else{
$('#msg').html(data.msg);
}
}
});
});
});


Controller

function isEmailExist(){
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
$msg = array(
'valid' => false,
'msg' => 'Email is already taken');
}else{
$msg = array(
'valid' => true,
'msg' => 'Username is available');
}
echo json_encode($msg);}


update controller

function isEmailExist(){
$email = $this->input->post('email');
$exists = $this->KulinerModel->isEmailExist($email);
if($exists){
echo "Email is already taken !";
}else{
$data = array(
'nama' => $this->input->post('nama'),
'email' => $email,
'password' => md5($this->input->post('password'))
);
$query = $this->KulinerModel->addMember($data);
redirect('/KulinerControl/');
}
}


Thanks in advance

Answer Source

you need to stop submitting your form at first then start checking. then if checking find its ok then submit it. i would use the following

$(document).ready(function(){
        $('#myform').on('submit', function(e) {
        e.preventDefault();        //<---- stop submiting the forms
        var email = $('#email').val();
        $.ajax({
            type: "POST",
            url: "<?php echo base_url()?>KulinerControl/isEmailExist",
            dataType: "json",
            data: "email="+email,                     
            success: function(data){
                if(data.valid){
                    $('#msg').html(data.msg);
                    $("#myform").submit();    //<---- submit the forms
                }else{
                    $('#msg').html(data.msg);
                }
            }
        });
    });
});
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download