chat app using jquery/ajax/php/oop codeigniter

Hi this question relates to a recent question I had posted that I'm trying to find at least some help with in general that leads to solve the entire problem. The following code is not mine and I had to fix it just to get it working to the extent it is now but the problem the algorithm within _get_chat_messages continues to execute the else condition. This doesn't make sense because there's chat message data in Mysql. I'm trying to make this source code work hoping it will lead me in the right direction with refreshing chat message content automatically without forcing browser client refreshes or redirecting headers.

What's causing _get_chat_messages to execute the else condition disregarding the if condition. The if conditions seems to evaluate to TRUE which doesn't make sense.

Any help much appreciated. Thanks.

//JQUERY/AJAX:

$(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;
    }
});

$("#submit_message").click(function() {
    var chat_message_content = $("input#chat_message").val();
    //this if condition seems to be ignored not sure why?
    if (chat_message_content == "") { return false; }

    $.post(base_url + "chat/ajax_add_chat_message", { chat_message_content : chat_message_content, chat_id : chat_id, user_id : user_id }, function(data) {

        if (data.status == 'ok')
        { 
            var current_content = $("div#chat_viewport").html();
            $("div#chat_viewport").html(current_content + data.message_content);

        }
        else
        {
            // there was an error do something 

        }

    }, "json");

    $("input#chat_message").val("");

    return false;
});


function get_chat_messages()
{

    $.post(base_url + "chat/ajax_get_chat_messages", { chat_id : chat_id }, function(data) {

        if (data.status == 'ok')
        {
            var current_content = $("div#chat_viewport").html();

            $("div#chat_viewport").html(current_content + data.message_content);

        }
        else
        {
            // there was an error do something 

        }

    }, "json");
}

get_chat_messages();

  });

//CONTROLLER:

   class Chat extends CI_Controller {

public function __construct()
{
    parent:: __construct();
    $this->load->model('chat_model');   
}

public function index()
{
    /* send in chat id and user id */

    $this->view_data['chat_id'] = 1;

    // check they are logged in
    if (! $this->session->userdata('logged_in')) {
        redirect('user/login');
    }

    $this->view_data['user_id'] = $this->session->userdata('user_id');

    $this->session->set_userdata('last_chat_message_id_' .    $this->view_data['chat_id'], 0);

    $this->view_data['page_title'] = 'web based chat app :)';
    $this->view_data['page_content'] = 'view_chat';
    $this->load->view('view_main', $this->view_data);   
}


public function ajax_add_chat_message()
{

    /* Scalar Variable data that needs to be POST'ed to this function
     * 
     * chat_id
     * user_id
     * chat_message_content
     *       * 
     */

    $chat_id = $this->input->post('chat_id');
    $user_id = $this->input->post('user_id');
    $chat_message_content = $this->input->post('chat_message', TRUE);

    $this->chat_model->add_chat_message($chat_id, $user_id,   $chat_message_content);

    // grab and return all messages
    $this->ajax_get_chat_messages($chat_id);
}

public function ajax_get_chat_messages($chat_id)
{
    $chat_id = $this->input->post('chat_id');

    echo $this->_get_chat_messages($chat_id);
}

private function _get_chat_messages($chat_id)
{
    $last_chat_message_id = (int)$this->session->userdata('last_chat_message_id_' . $chat_id); 

    $chat_messages = $this->chat_model->get_chat_messages($chat_id, $last_chat_message_id);

    if ($chat_messages->num_rows() > 0)
    {
        // store the last chat message id
        $last_chat_message_id = $chat_messages->row($chat_messages->num_rows() - 1)->chat_message_id;

        $this->session->set_userdata('last_chat_message_id_' . $chat_id, $last_chat_message_id);

        // we have some chat let's return it

        $chat_messages_html = '<ul>';

        foreach ($chat_messages->result() as $chat_message)
        {
            $li_class = ($this->session->userdata('user_id') == $chat_message->user_id) ? 'class="by_current_user"' : '';

            $chat_messages_html .= '<li ' . $li_class . '>' . '<span class="chat_message_header">' . $chat_message->chat_message_timestamp . ' by ' . $chat_message->name . '</span><p class="message_content">' .  $chat_message->chat_message_content . '</p></li>';
        }

        $chat_messages_html .= '</ul>';

    $result = array('status' => 'ok', 'content' =>    $chat_messages_html);
        //header('Content-Type: application/json',true);
        return json_encode($result);
        exit();
    }
    else
    {
        // we have no chat yet
        $result = array('status' => 'no chat', 'content' => '');
        //header('Content-Type: application/json',true);
        return json_encode($result);
        exit();
    }
 }

  }

//MODEL:

    class chat_model extends CI_Model {

public function __construct()
{
    parent::__construct();
}

public function add_chat_message($chat_id, $user_id, $chat_message_content)
{
    $query_str = "INSERT INTO chat_messages (chat_id, user_id,  chat_message_content) VALUES (?, ?, ?)";

    $this->db->query($query_str, array($chat_id, $user_id, $chat_message_content));
}

public function get_chat_messages($chat_id, $last_chat_message_id = 0)
{
    $query_str = "SELECT
                cm.chat_message_id,
                cm.user_id,
                cm.chat_message_content,
                DATE_FORMAT(cm.create_date, '%D of %M %Y at %H:%i:%s') AS chat_message_timestamp,
                u.name
                FROM chat_messages cm
                JOIN users u ON cm.user_id = u.user_id
                WHERE cm.chat_id = ?
                and cm.chat_message_id > ?
                ORDER BY cm.chat_message_id ASC";

    $result = $this->db->query($query_str, array($chat_id, $last_chat_message_id));

    return $result;
}
} 

//VIEW FILE HENCE VIEW_CHAT.PHP

    <html>
    <head>
    <script type="text/javascript" src="/js/jquery-1.4.2.min.js"></script>
    <script type="text/javascript" src="<?php echo base_url() . 'public/';?>chat.js">   
    </script>
    <script type="text/javascript">

    var base_url = "<?php echo base_url();?>";

    var chat_id = "<?php echo $chat_id; ?>";
    var user_id = "<?php echo $user_id; ?>";

    </script>
    </head>
    <body>

     <style type="text/css">

     div#chat_viewport {
 font-family:Verdana, Arial, sans-serif;
 padding:5px;
 border-top:2px dashed #585858;
 min-height:300px;
 color:black;
 max-height:650px;
 overflow:auto;
 margin-bottom:10px;
 width:750px;
}

    div#chat_viewport ul {
list-style-type:none;
padding-left:10px;
  }

    div#chat_viewport ul li {
margin-top:10px;
width:85%;
  }

    span.chat_message_header {
font-size:0.7em;
font-family:"MS Trebuchet", Arial, sans-serif;
color:#547980;
 }

    p.message_content {
margin-top:0px;
margin-bottom:5px;
padding-left:10px;
margin-right:0px;
}

    input#chat_message {
margin-top:5px;
border:1px solid #585858;
width:70%;
font-size:1.2em;
margin-right:10px;
  }

   input#submit_message {
font-size:2em;
padding:5px 10px;
vertical-align:top;
margin-top:5px;
 }

    div#chat_input { margin-bottom:10px; }

    div#chat_viewport ul li.by_current_user span.chat_message_header {
color:#e9561b;
}

   </style>


  <h1>Let's do some chatting :D</h1>

  <div id="chat_viewport">

  </div>

  <div id="chat_input">
  <?php echo form_open('chat/ajax_add_chat_message'); ?>
  <input id="chat_message" name="chat_message" type="text" value="" tabindex="1" />
  <?php echo form_submit('submit_message','submit_message'); ?>
  <?php echo anchor('#', 'Say it', array('title' => 'Send this chat message', 'id' => 'submit_message'));?>
<div class="clearer"></div>
  <?php echo form_close(); ?>
  </div>
  </body>
  </html>

I am not sure but I have a feeling that the json that you receive from the server is not formatted properly. See this: jQuery won't parse my JSON from AJAX query

链接地址: http://www.djcxy.com/p/46106.html

上一篇: JavaScript返回undefined

下一篇: 使用jquery / ajax / php / oop codeigniter聊天应用程序