doucitan2544 2014-06-05 07:28
浏览 62
已采纳

Codeigniter ajax调用错误

I'm trying to make an ajax call to get result from my database, but i'm facing an error.

My javascript:

<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script language="Javascript">
setTimeout(makeAjaxCall, 1000);
function makeAjaxCall(){
$.ajax({
    type: "post",
    url: "call/update",
    cache: false,               
    data: {action: 'getUpdate', term: '<?php echo $id;?>'},
    success: function(json){                        
    try{        
        var obj = jQuery.parseJSON(json);
        alert( obj['STATUS'] + obj['results']);


    }catch(e) {     
        alert('Exception while request..');
    }       
    },
    error: function(){                      
        alert('Error while request..');
    }
 });
}
</script>

And my controller's method:

public function update()
{
    if (isset($_POST['action'])){
        if ($_POST['action'] == 'getUpdate'){
            pollNewData();
        }
    }

    function pollNewData(){
        $term = $_POST['term'];
        $query = $this->db->query("SELECT * FROM users where guid  <> '' and user_id = '$term'");
        $res = $query->result();
        echo json_encode(array('STATUS'=>200, 'results'=>$res));
    }

}

i have this error on chrome debugs tool:

500 (Internal Server Error)

  • 写回答

2条回答 默认 最新

  • douh9817 2014-06-05 08:00
    关注

    You have several issues. Below is the working code:

    public function update()
    {
    
        if(!function_exists('pollNewData')){ // don't redeclare if already exists
            function pollNewData($db){ // pass $db
                $term = $_POST['term'];
                $query = $db->query("SELECT * FROM users where guid  <> '' and user_id = '$term'");
                $res = $query->result();
                echo json_encode(array('STATUS'=>200, 'results'=>$res));
            }
        }
    
        if (isset($_POST['action'])){
            if ($_POST['action'] == 'getUpdate'){
                pollNewData($this->db); // pass $this->db
            }
        }
    
    }
    

    Changes:

    • Moved the function definition to before it is called - it must exist before calling.
    • The $this context is not set in the function, so pass the $db object as an argument.
    • When defining functions inside a class method, you must have a function_exists() check because on the second call, it will try to redeclare the function and produce a fatal error.

    For future debugging you should turn errors on:

    error_reporting(E_ALL);
    ini_set('display_errors', '1');
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路