CodeIgniter:唯一的电话号码在AJAX中检查



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

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;
} 
 }  

模型

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();">

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

$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;

尝试一些修改:

控制器

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>
if(count($phone) > 0)
{
    return false;
}
else
{
    return true;
}

您需要检查返回是否大于0,因为如果值不为null或False

,是否将返回true

最新更新