当前位置: 动力学知识库 > 问答 > 编程问答 >

php - Ajax long polling with Codeigniter and mysql

问题描述:

I am attempting to implement a simple chat application using ajax long polling with codeigniter framework. Below is the ajax request

var timestamp = null;

function check_incoming_chat_message(me, timestamp) {

$.ajax({

type: "Get",

dataType: 'json',

url: 'http://localhost/ci/index.php/chat/check_chatbox?to_me='+me+'&timestamp='+timestamp,

async: true,

//data: {to_me: me, timestamp: timestamp},

cache: false,

success: function(response) {

setTimeout(check_incoming_chat_message(response.to_chat, response.timestamp),10000);

},

error: function(response) {

setInterval(check_incoming_chat_message(response.to_chat, response.timestamp),2000);

},

complete: function() {

}

});

}

And below is the code at the controller end, in which the control keeps looping checking the db, unless there is a new chat message in the mysql in which case it throws the chat message to the view. And once i get the chat message at the view, i trigger the ajax request again.(atleast thats my idea)

function check_chatbox() {

$logged_in_user = $_GET["to_me"];

$last = $_GET["timestamp"];

header('Content-type: text/plain');

header('Content-type: application/json');

if($last == "" || $last == null) { // check if timestamp is null

$result = $this->chat_model->current_tstamp($logged_in_user);

foreach($result as $row)

{

$data = array('msg_time' => $row->msg_time,

'chat_message' => '',

'to_chat' => $logged_in_user

);

}

echo json_encode($data);

return;

}

$result = $this->chat_model->current_tstamp($logged_in_user);

foreach($result as $row)

{

$data_array = array('msg_time' => $row->msg_time);

}

$current = $data_array['msg_time'];

while($current <= $last) {

usleep(100000);

//clearstatcache();

$result = $this->chat_model->current_tstamp($logged_in_user);

foreach($result as $row)

{

$data = array('msg_time' => $row->msg_time);

}

$current = $data['msg_time'];

}

$result = $this->chat_model->check_new_messages($logged_in_user, $current);

if($result) {

foreach($result as $row)

{

$data = array('chat_message' => $row->chat_message,

'from_chat' => $row->from_chat,

'chat_id' => $row->chat_id,

'msg_time' => $row->msg_time

);

}

echo json_encode($data);

return;

}

else {

return;

}

}

The problem is that, it blocks all the other requests in the page, including hyperlinks(as in anchor tags in codeigniter).Can someone please help me point out as to what i am doing wrong?

Thanks

Note: I am trying to replicate the same procedure used in this example

http://www.mediafire.com/download/3xd0zx5ej3pp42b/comet.zip

分享给朋友:
您可能感兴趣的文章:
随机阅读: