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)

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');

Some suggestions:

 url: "<?php echo base_url();?>call/update",

 //pollNewData();
 echo $this->pollNewData(); //call like this and echo it out to the ajax

//echo json_encode(array('STATUS'=>200, 'results'=>$res));
return json_encode(array('STATUS'=>200, 'results'=>$res)); //return it instead to the calling function