Hi I successfully designed a chat message system between users and it works fine. The only problem I am having at this point is polling data from chat table to browser real time.
The messages are displayed using ajax and the setInterval works as I checked the console. The issue is that it does not capture new entries to the table for display and hence the user has to keep refreshing the page to see new content.
Please help. My code is below. Please forgive my file naming convention as I will change it later on. PS this is developed using codeigniter framework.
Chats.php - Controller
public function ajax_get_chat_messages(){ echo $this->_get_chat_messages(); } function _get_chat_messages($recipient = null) { $user_id = $this->session->userdata('user_id'); $recipient = $this->input->post('recipient'); $data['recipient'] = $this->User_model->get_users($user_id); $data['chats_count'] = $this->Chats_model->get_chat_messages_count($recipient); $content = $this->Chats_model->get_chat_messages_count($recipient); $data['chats'] = $this->Chats_model->get_chat_messages($user_id); $result = array('status' =>'ok', 'content'=>$content); return json_encode($result); }
Model - Chats_model.php
public function get_chat_messages_count($recipient = null){ $session = $this->session->userdata('user_id'); $this->db->select('*'); $this->db->from('chat_messages'); $this->db->join('users', 'users.user_id = chat_messages.user_id'); $this->db->where(array('chat_messages.user_id' => $session)); $this->db->where(array('chat_messages.recipient' => $recipient)); $this->db->or_where(array('chat_messages.user_id' => $recipient)); $this->db->where(array('chat_messages.recipient' => $session)); $this->db->where_in(array('chat_messages.chat_id' => $session , $recipient)); $query = $this->db->get(); return $query->result_array(); }
View - chats_view.php
<script type="text/javascript"> var user = "<div class='timeline-item' id='view'><ul><?php foreach($chats_count as $chat){echo '<li>'; echo $chat['username']; echo '</li>'; }?></ul></div>"; </script> <div class="wrapper wrapper-content"> <div class="row animated fadeInRight"> <div class="col-lg-12"> <div class="ibox float-e-margins"> <div class="ibox-title"> <h5>Chat</h5> <div class="ibox-tools" > </div> </div> <div class="ibox-content inspinia-timeline" id="view1" > </div> </div> </div> </div> </div> </div> </div> </div>
JS - chat2.js
$(document).ready(function(){ setInterval(function() { get_chat_messages(); }, 2500) $("input#chat_message").keypress(function(e){ if(e.which == 13){ $("a#submit_message").click(); return false; } }); function get_chat_messages(){ $.post(base_url +"user/chats/ajax_get_chat_messages",{user: user}, function(data) { if(data) { var current_content = $("#view1").html(); $("#view1").html(user); console.log(user); } else { }, "json"); } get_chat_messages(); });