简体   繁体   English

如果数据库中的数据不匹配,Codeigniter Ajax将不返回任何错误消息

[英]Codeigniter Ajax not returning any error message if the data is not matched in database

I am working with AJAX in CodeIgniter. 我正在CodeIgniter中使用AJAX。

Here is my code. 这是我的代码。 This is working when my SQL query returns a result. 当我的SQL查询返回结果时,此方法有效。 If the query is empty, AJAX doesn't return anything. 如果查询为空,则AJAX不返回任何内容。

My Model: 我的模特:

function view_filter_by_cat($id){
$sql = "SELECT * FROM ".TBL_FILTER_OPTION." WHERE FID=?";
$query=$this->db->query($sql,$id);
if($query->num_rows()){
    foreach ($query->result() as $row){
        $result[] = $row;
    }           
    $query->free_result();
    return $result;         
}

AJAX Controller: AJAX控制器:

public function find_filters_options(){
    if($this->input->post('FID')){
        $fid = $this->input->post('FID');
        $filterList= $this->filter_option_model->view_filter_by_cat($fid);          
        if($this->filter_option_model->view_filter_by_cat($fid)){               
            echo (json_encode($filterList));
        }else{              
            echo '0';
        }
    }
}

Ajax calling: Ajax调用:

$.ajax({
    type: "POST",
    url: '<?php echo site_url('admin/products/find_filters_options'); ?>',
    data: {
        <?php echo $this->security->get_csrf_token_name(); ?> : '<?php echo $this->security->get_csrf_hash(); ?>',
        FID: fid
    },
    success: function(data1){
        alert(data1);
    }
});

My question is when the query doesn't return any value, I am unable to access the success message. 我的问题是,当查询不返回任何值时,我将无法访问成功消息。 I want to get the value '0', when the return is empty. 当返回为空时,我想获取值“ 0”。

you could change you controller to like: 您可以将控制器更改为:

public function find_filters_options(){
  $result = array();
    if($this->input->post('FID')){
        $fid = $this->input->post('FID');
        $filterList= $this->filter_option_model->view_filter_by_cat($fid);          
        if($this->filter_option_model->view_filter_by_cat($fid)){               
            $result["got_data"] = "yes";
            $result["data"] = $filterList;            
        }else{              
            $result["got_data"] = "no";
        }
    }
    else {
      $result["got_data"] = "no";
    }
    echo (json_encode($result));
}

And your jquery ajax 还有你的jQuery Ajax

$.ajax({
  type: "POST",
  url: '<?php echo site_url('admin/products/find_filters_options'); ?>',
  data : {<?php echo $this->security->get_csrf_token_name(); ?> : '<?php echo 
$this->security->get_csrf_hash(); ?>', FID : fid },
  dataType: "json",
  success: function(data1) {
    if(data1.got_data == "yes") {
        var data = data1.data; //get data from server here
    } 
    else {
       //dont have any data
       //show some appropriate message
    }
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM