Jquery json request and Kohana
I am trying to learn a little bit of jquery and more about the kohana framework. Ok so I wrote a simple test script to grab some entries from a database. The php works as in it returns the r开发者_如何学Cow in a json format, but I guess my jquery isn't working.
The json is suppose to return multiple rows so I want it to add all of those into the #chats div. Here is my jquery code:
$(document).ready(function() {
$.getJSON('json/get_chat_entries/1',
function(data) {
$('#chats').append('<li>' + data.text + '</li>');
}
});
});
The get entries code is suppose to grab all the entries in the database matching the chat_id. Write now it seems to be only returning the first entry. here is my get entries code:
function get_entries() {
$entries = $result = DB::select() - > from('chat_entries') - > where('chat_id', '=', $this - > chat_id) - > execute() - > current();
return $entries;
}
And this is the controller code:
public function action_get_chat_entries(){
$chat_id = $this->request->param('id');
$chat = new Model_Chat($chat_id);
echo json_encode($chat->get_entries());
}
Just remove ->current()
from your get_entries()
method.
Cleaned up a bit:
Model:
public function get_entries()
{
if (!$this->_loaded)
return array();
return DB::select()
->from('chat_entries')
->where('chat_id', '=', $this->chat_id)
->execute($this->_db);
}
Controller:
public function action_get_chat_entries()
{
$id = $this->request->param('id', FALSE);
$chat = new Model_Chat($id);
$this->request->headers['Content-Type'] = 'application/json';
$this->request->response = json_encode($chat->get_entries());
}
$results = DB::select(...)->from(...)->where(...)->execute();
echo json_encode(iterator_to_array($results));
精彩评论