Jc John Jc John - 1 month ago 11
Ajax Question

check email if valid/duplicate from database using codeigniter

i have a code from tutorial that doesn't work well. I don't know why, i am a beginner in codeigniter. I want to submit the button update, if duplicate a text will response below the textbox that the email is exist and also check it if the email is a valid email syntax.

Here is my html code :

<form id="reg_form" class="form-horizontal">
<div class="form-group">
<label class="control-label col-sm-3" for="curEmail">New Email</label>
<div class="col-sm-6">
<input type="text" class="form-control" name="email" id="email" placeholder="youremail@yourcompany.com" required data-fv-emailaddress-message="The value is not a valid email address">
</div>
<div class="col-sm-8 ajax_response_result"></div>
</div>
<button onclick="editEmail()" class="btn btn-success btn-sm "><i class="fa fa-refresh"></i> Update Profile</button>
</form>


Here is my ajax:

function editEmail() {

jQuery.ajax({
type: "POST",
url: "<?php echo site_url('manager/profile/check_email') ?>",
data: $("#reg_form").serialize(),
success: function(res) {
$(".ajax_response_result").html(res);

}
});

}


My CodeIgniter Controller:

public function check_email() {
$this->form_validation->set_rules('email', 'Email', 'required|is_unique[user.user_email]|valid_email');

$this->form_validation->set_message('is_unique', 'The %s is already taken');
if ($this->form_validation->run() == FALSE):
echo 'Enter valid email.';
else :
unset($_POST);
echo 'Available';
endif;

}

Answer

There are several issue in your code, Revised & given below

HTML (method POST was not there in your code, editEmail here event missing etc etc)

<form id="reg_form" class="form-horizontal" method="POST">
    <div class="form-group">
    <label class="control-label col-sm-3" for="curEmail">New Email</label>
    <div class="col-sm-6">
    <input type="text" class="form-control" name="email" id="email" placeholder="youremail@yourcompany.com" required data-fv-emailaddress-message="The value is not a valid email address">                                                           
    </div>
    <div class="col-sm-8 ajax_response_result"></div>                                                       
    </div>
    <button onclick="editEmail(event)" class="btn btn-success btn-sm "><i class="fa fa-refresh"></i> Update Profile</button>
</form>

Now JS (e.preventDefault(); used for prevent form submitting etc etc)

function editEmail(e) {
    e.preventDefault();
    jQuery.ajax({
    type: "POST",
    url: "<?php echo site_url('manager/profile/check_email') ?>",    
    data: $("#reg_form").serialize(),
    success: function(res) {
     $(".ajax_response_result").html(res);

     }
    });

}
Comments