Codeigniter:ajax中唯一的电话号码检查

时间:2017-06-01 06:18:21

标签: php jquery ajax codeigniter

我在检查数据库中存在的唯一电话号码时遇到问题。在提交时,它会检测我输入的每个数字作为数据库中的数字,即使它不存在。附上以下代码:

AJAX

<script>
function checkdata(){
var tel = $('.tel').val();      
var x;
if(tel){
$.ajax({
   url: '<?php echo base_url('index.php/admin/customer/check_phone_availibility1'); ?>',
   data:{tel:tel},
   error: function() {
  alert("An error has occurred.");
   },
   success: function(data) {   
    x= data;

    },
   type: 'POST'
});
if(!x){
alert('This phone exists in database');
$('.tel').val("");
return false;
}
}
}   
</script>

控制器

public function check_phone_availibility1(){
$tel = $this->input->post('tel');
$success = $this->customer_m->check_phone_no_availability($tel);
if($success){
    echo true;
}
else {
    echo false;
} 
 }  

MODEL

public function check_phone_no_availability($phone){
$query = $this->db->query("SELECT * from customers WHERE phone='$phone'"); 
$phone = $query->result();

if(count($phone))
{
    return false;
}
else
{
    return true;
}       

}

查看

<input type="text" name="phone" value="" class="form-control tel" id="phone" maxlength="10" required="">
<input type="submit" name="submit_btn" value="Save Customer" class="btn btn-success" onclick="return checkdata();">

如果可以解决这个问题,我将非常感激。感谢

3 个答案:

答案 0 :(得分:0)

$var = false;
$var2 = '';
$var3 = null;

产生

count($var) => 1
count($var) => 1
count($var) => 0

因此,在您的模型中,您可以检查您的查询是否生成了任何结果,您可以执行以下操作:

$query = $this->db->query("SELECT * from customers WHERE phone='$phone'"); 
$query_result= $query->result();

return (count($query_result) > 1) ? true : false;

或者,只是

return ($query_result) ? true : false;

答案 1 :(得分:0)

尝试进行一些修改:

<强>控制器

public function check_phone_availibility1(){
$tel = $this->input->post('tel');
$success = $this->customer_m->check_phone_no_availability($tel);
if($success->num_rows() == 0){
  echo 1;
}
else {
  echo 0;
} 
} 

<强>模型

public function check_phone_no_availability($phone){
return $this->db->query("SELECT * from customers WHERE phone='$phone'"); 
}

<强> AJAX

<script>
function checkdata(){
var tel = $('.tel').val();      
var x;
if(tel){
$.ajax({ url: '<?php echo base_url('index.php/admin/customer/check_phone_availibility1'); ?>',
data:{tel:tel},
error: function() {
alert("An error has occurred.");
},
success: function(data) {   
 x= data;

 },
type: 'POST'
});
if(x != "1"){
alert('This phone exists in database');
$('.tel').val("");
return false;
}
}
}   
</script>

答案 2 :(得分:0)

if(count($phone) > 0)
{
    return false;
}
else
{
    return true;
}

你需要检查返回是否大于0,因为if如果值不为null或false则返回true