Direct to the point. I am checking that my entered username exists or not exist in the database. So I have decided to use ajax.
The expected result is like when I enter the username which already exists then the div style get change and error message get appear under it but this is not happing now I don't know why?
I am not familiar with ajax so any syntax missing or any wrong technique you see then you can point it out.
This is my controller Function:
function check_userName_exists()
{
$user_name = $this->input->post('user_name');
log_message('debug', 'Posted Username by Ajax for Check it exist or not : '. print_r($user_name, TRUE));
$exists = $this->student_db->check_user_name($user_name);
log_message('debug', 'Username Exist or not Response array: '. print_r($exists, TRUE));
$count = count($exists);
// echo $count
log_message('debug', 'Username Exist or not Response Count: '. print_r($count, TRUE));
if ($count == 1) {
$data['unique'] = 1;
print(json_encode($data));
} else {
$data['unique'] = 0;
print(json_encode($data));
}
}
This is my model function:
function check_user_name($user_name)
{
$this->db->select('user_name');
$this->db->from('user');
$this->db->where('user_name', $user_name);
$query = $this->db->get();
$query_last = $this->db->last_query();
log_message('debug', 'Find UserName is Unique Or Not Query: '. print_r($query_last, TRUE));
$result = $query->result_array();
log_message('debug', 'Find UserName is Unique Or Not Result: '. print_r($result, TRUE));
return $result;
}
This is the Ajax script:
<script type="text/javascript">
function check_if_exists() {
var user_name = $("#user_name").val();
// console.log(user_name);
$.ajax({
type:'POST',
url: "<?php echo site_url('student/check_userName_exists'); ?>",
data:{ 'user_name':user_name},
success:function(response)
{
if (response.unique = 1)
{
// alert(success);
//console.log(response);
$("#userNameDiv").addClass("has-warning");
$("#user_name").addClass("form-control-danger");
$("#userNameErrorMsg").text("This User Name Is Already Takken. Please Try Something Else.");
}
else
{
$("#userNameDiv").removeClass("has-warning");
$("#user_name").removeClass("form-control-danger");
$('#userNameErrorMsg').text('');
}
}
});
};
This is my HTML:
<div class="form-group" id="userNameDiv">
<input type="text" class="form-control form-control-success" name="user_name" required id="user_name" placeholder="Enter Username" onblur="check_if_exists();">
<small class="text-help" id="userNameErrorMsg"></small>
</div>
got blank response in console.
return 1andreturn 0in your controller toecho '1'andecho '0'. Controller function in CI does not return the response, it should output it.