1

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>
PeeHaa
  • 71,436
  • 58
  • 190
  • 262
eNigma
  • 101
  • 4
  • 10
  • Please, cut it down. It's not even clear what part of that wall of code relates to your question and what doesn't. Provide the smallest possible relevant code sample you can that makes sense. Just a ton of code with no real way for us to run and test it is not helpful to anybody. – deceze Oct 02 '12 at 05:09
  • There's a lot of code that has to be there to understand the algo's and thorough understanding of the languages involved. I had the explained the problems above before the source code. – eNigma Oct 02 '12 at 05:15
  • 3
    @eNigma THERE'S NO NEED TO SHOUT, I'M SITTING RIGHT HERE – DaveRandom Feb 27 '13 at 21:28

1 Answers1

0

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

Community
  • 1
  • 1
Ulan Murzatayev
  • 870
  • 5
  • 15
  • Hi Ulan I tried what Tomalak had posted which was an accepted answer but it didn't work for. Another strange fact I check to make sure jquery is actively working and it is however there's a part of logic I mentioned above that seems to be skipped. Anyhow thanks so much for the help so far. – eNigma Oct 02 '12 at 20:37
  • Hi Ulan in the post the following was the accepted answer: header('Content-Type: application/json'); Is this correct? – eNigma Oct 02 '12 at 20:42
  • This could be the case, but I don't think that this will change anything for you. As far as I know JQuery is not so good at parsing JSON strings provided by PHP, since it may escape some characters in the way JQUEry does not understand. Just try to modify your Controller code to: `echo "{'status':'ok', 'message_content': 'some message'}";` instead of `echo $this->_get_chat_messages($chat_id);`. See if this works, than you probably need to get the data in your post as a string and parse it there using some plugin like http://code.google.com/p/jquery-json/ – Ulan Murzatayev Oct 02 '12 at 23:57
  • hey what's up Ulan. Yah I'm going try your suggestions. I found some some more problems with the source code which I had to fix. It's 10:00 PM my time so I'm gonna start on your suggestions and then see where that leads things. Then I'll post tomorrow with the result and tell you where I am at essentially. – eNigma Oct 03 '12 at 05:18
  • hey Ulan I found quite a few different problems with the chap app I had posted. The software isn't mine and I had to modify it just to get it where it had been before I had post the problem. I have private networking stream that's really great and utilizes CI. However it doesn't have jquery implemented yet to keep conversations in real-time. I think I am going to have to do the jquery/ajax from scratch for this software which feels like reinvesting the wheel but not sure what else to do. Probably will have to post a new question involving this if I get stuck. – eNigma Oct 08 '12 at 21:34
  • probably will get stuck with jquery/ajax part. I did conclude I think the most robust way is to do Reverse Ajax long-polling for the stream. If you know any excellent examples utilizing CI it will help. I haven't been able to find any. I only found only one on screenr which doesn't include Mysql. The chat using a file based chat log. Essentially it is Php and Reverse Ajax Long Polling. – eNigma Oct 08 '12 at 21:34
  • probably will get stuck with jquery/ajax part. I did conclude I think the most robust way is to do Reverse Ajax long-polling for the stream. If you know any excellent examples utilizing CI it will help. I haven't been able to find any. I only found only one on screenr which doesn't include Mysql. The chat using a file based chat log. Essentially it is Php and Reverse Ajax Long Polling. According to the code the chat log is file based. I'm thinking the code for the file based part I could change to Mysql based but it sure would be easier if I could find a more relevant tutorial or something. – eNigma Oct 08 '12 at 21:43
  • Also plan to look into the jquery plugins some more since you said jquery has trouble parsing JSON strings provided by Php. – eNigma Oct 08 '12 at 21:43