3

I am trying to implement a chat application using the codeigniter framework but on form submit, the form data does not get submitted and the submit button becomes disabled. when I check on the javascript console, I get an error 500 Internal Server Error for the url localhost/biko/chat/conv/xsapSHKs/msg which should fetch new messages. I am pretty conversant with PHP but am not pretty good with ajax or javascript. Any assistance will be highly appreciated. Below is my Controller, model and view.

Controller (chat.php)

public function conv($slug = FALSE, $action = FALSE) {
    $this->form_validation->set_rules('message', 'Message', 'trim|required');
    $this->form_validation->set_rules('mid', '', 'trim|required');
    $this->form_validation->set_rules('fid', '', 'trim|required');
    $this->form_validation->set_rules('id', '', 'trim|required');
    if ($slug === FALSE) {
        if ($_POST['bcdhgfjhggvgzs'] != '') {
            $this->Chat_model->startConv();
            redirect('/conv/chat/'.$_POST['bcdhgfjhggvgzs'], 'refresh');
        }
    } else {
        if ($action !== '' and $this->form_validation->run() !== FALSE) {
            $this->Chat_model->save($action);
        }
        $data['pageTitle'] = 'Chat';                
        $data['pageKeywords'] = 'chat';
        $data['pageDescription'] = 'Chat with Us';
        $data['converse'] = $this->Chat_model->get_conversations($slug);
        $data['ifempty'] = count($data['converse']);
        $data['content'] = "chat/chatty";
        $this->load->view($this->frontend_template, $data);
    }
}

Model

public function save($action) {
    $from = $this->input->post('mid', TRUE);
    $descId = $this->input->post('id', TRUE);
    $to = $this->input->post('fid', TRUE);
    $msg = $this->input->post('text', TRUE);
    $created = mktime();
    
    switch ($action):
    case 'new':
        $descId = $this->input->post('id', TRUE);
        $created = mktime();
        $msg = $this->input->post('text', TRUE);
        $from = $this->input->post('mid', TRUE);
        $to = $this->input->post('fid', TRUE);
        if(empty($msg)){
            $json = array('status' => 0, 'msg'=> 'Enter your message!.');
        }else{
            $data = array (
                'desc_id' => $descId,
                'from' => $from,
                'to' => $to,
                'msg' => $msg,
                'time' => $created,
                'status' => '1'
            );      
            $qur = $this->db->insert('chat_msg', $data);
            $insertId = $this->db->insert_id();
            if($qur){
                $this->db->where('id', $insertId);
                $qurGet = $this->db->get('chat_msg');
                while($row = $qurGet->row_array()){
                    $json = array('status' => 1, 'msg' => $row['msg'], 'lid' => $insertId, 'time' => $row['time']);
                }
            } else {
                $json = array('status' => 0, 'msg'=> 'Unable to process request.');
            }
        }
    break;
    case 'msg':
        $from = $this->input->post('mid', TRUE);
        $to = $this->input->post('fid', TRUE);
        $lid = $this->input->post('lid', TRUE);
        if(empty($from)){

        } else {
            //print_r($_POST);
            $where = array('to' => $to, 'from' => $from, 'status' => '1');
            $this->db->where($where);
            $qur = $this->db->get('chat_msg');
            if($qur->num_rows() > 0){
                $json = array('status' => 1);
            }else{
                $json = array('status' => 0);
            }
        }
    break;
    case 'NewMsg':
        $from = $this->input->post('mid', TRUE);
        $to = $this->input->post('fid', TRUE);
        
        $where = array('to' => $to, 'from' => $from, 'status' => '1');
        $this->db->where($where);
        $this->db->order_by('id', 'desc');
        $this->db->limit(1);
        $qur = $this->db->get('chat_msg');

        while($rw = $qur->row_array()){
            $json = array('status' => 1, 'msg' => '<div>'.$rw['msg'].'</div>', 'lid' => $rw['id'], 'time'=> $rw['time']);
        }
        // update status
        $where = array('to' => $to, 'from' => $from);
        $this->db->where($where);
        $qur = $this->db->update('chat_msg');
    break;
endswitch;
$this->output->set_content_type('application/json');
return $this->set_output($json);
}

view

    <?php
if ($this->auth_user_id != $converse['from']) { $fid = $this->auth_user_id; } else { $fid = $converse['to']; }
$myid = $this->auth_user_id;
?>
<script src="<?php echo WEBSITE_URL ?>assets/chat/jquery.min.js"></script>
<script src="<?php echo WEBSITE_URL ?>assets/chat/moment.min.js"></script>
<script src="<?php echo WEBSITE_URL ?>assets/chat/livestamp.js"></script>
<link rel="stylesheet" type="text/css" href="<?php echo WEBSITE_URL ?>assets/chat/style.css">
<div class="chatcontainer">
      <div class="chat" id="chat">
        <div class="stream" id="cstream">

      </div>
      </div>
      <div class="msg">
          <form method="post" id="msenger" action="">
            <textarea name="msg" id="msg-min"></textarea>
            <input name="id" type="hidden" value="<?php echo $converse['id'] ?>" />
            <input type="hidden" name="mid" value="<?php echo $myid;?>">
            <input type="hidden" name="fid" value="<?php echo $fid;?>">
            <input type="submit" value="Send" id="sb-mt">
          </form>
      </div>
      <div id="dataHelper" last-id=""></div>
  </div>
<script type="text/javascript">
$(document).keyup(function(e){
    if(e.keyCode == 13){
        if($('#msenger textarea').val().trim() == ""){
            $('#msenger textarea').val('');
        }else{
            $('#msenger textarea').attr('readonly', 'readonly');
            $('#sb-mt').attr('disabled', 'disabled');   // Disable submit button
            sendMsg();
        }       
    }
}); 

$(document).ready(function() {
    $('#msg-min').focus();
    $('#msenger').submit(function(e){
        $('#msenger textarea').attr('readonly', 'readonly');
        $('#sb-mt').attr('disabled', 'disabled');   // Disable submit button
        sendMsg();
        e.preventDefault(); 
    });
});

function sendMsg(){
    $.ajax({
        type: 'post',
        url: '<?php echo WEBSITE_URL .''. uri_string() ?>/new',
        data: $('#msenger').serialize(),
        dataType: 'json',
        success: function(rsp){
                $('#msenger textarea').removeAttr('readonly');
                $('#sb-mt').removeAttr('disabled'); // Enable submit button
                if(parseInt(rsp.status) == 0){
                    alert(rsp.msg);
                }else if(parseInt(rsp.status) == 1){
                    $('#msenger textarea').val('');
                    $('#msenger textarea').focus();
                    //$design = '<div>'+rsp.msg+'<span class="time-'+rsp.lid+'"></span></div>';
                    $design = '<div class="float-fix">'+
                                    '<div class="m-rply">'+
                                        '<div class="msg-bg">'+
                                            '<div class="">'+
                                            'Me'+
                                            '</div>'+
                                            '<div class="msgA">'+
                                                rsp.msg+
                                                '<div class="">'+
                                                    '<div class="msg-time time-'+rsp.lid+'"></div>'+
                                                    '<div class="myrply-i"></div>'+
                                                '</div>'+
                                            '</div>'+
                                        '</div>'+
                                    '</div>'+
                                '</div>';
                    $('#cstream').append($design);

                    $('.time-'+rsp.lid).livestamp();
                    $('#dataHelper').attr('last-id', rsp.lid);
                    $('#chat').scrollTop($('#cstream').height());
                }
            }
        });
}
function checkStatus(){
    $fid = '<?php echo $fid; ?>';
    $mid = '<?php echo $myid; ?>';
    $.ajax({
        type: 'post',
        url: '<?php echo WEBSITE_URL .''. uri_string() ?>/msg',
        data: {fid: $fid, mid: $mid, lid: $('#dataHelper').attr('last-id')},
        dataType: 'json',
        cache: false,
        success: function(rsp){
                if(parseInt(rsp.status) == 0){
                    return false;
                }else if(parseInt(rsp.status) == 1){
                    getMsg();
                }
            }
        }); 
}

// Check for latest message
setInterval(function(){checkStatus();}, 200);

function getMsg(){
    $fid = '<?php echo $fid; ?>';
    $mid = '<?php echo $myid; ?>';
    $.ajax({
        type: 'post',
        url: '<?php echo WEBSITE_URL .''. uri_string() ?>/NewMsg',
        data:  {fid: $fid, mid: $mid},
        dataType: 'json',
        success: function(rsp){
                if(parseInt(rsp.status) == 0){
                    //alert(rsp.msg);
                }else if(parseInt(rsp.status) == 1){
                    $design = '<div class="float-fix">'+
                                    '<div class="f-rply">'+
                                        '<div class="msg-bg">'+
                                            '<div class="">'+
                                            $fid+
                                            '</div>'+
                                            '<div class="msgA">'+
                                                rsp.msg+
                                                '<div class="">'+
                                                    '<div class="msg-time time-'+rsp.lid+'"></div>'+
                                                    '<div class="myrply-f"></div>'+
                                                '</div>'+
                                            '</div>'+
                                        '</div>'+
                                    '</div>'+
                                '</div>';
                    $('#cstream').append($design);
                    $('#chat').scrollTop ($('#cstream').height());
                    $('.time-'+rsp.lid).livestamp();
                    $('#dataHelper').attr('last-id', rsp.lid);  
                }
            }
    });
}
</script>

Javascript Console Screenshot Screenshot of the javascript console

Community
  • 1
  • 1
Biko
  • 332
  • 3
  • 15
  • possible duplicate of [codeigniter CSRF error: "The action you have requested is not allowed."](http://stackoverflow.com/questions/21214612/codeigniter-csrf-error-the-action-you-have-requested-is-not-allowed) – viral Jul 07 '15 at 09:31
  • I tried out the solutions offered in that question but none of them worked. – Biko Jul 07 '15 at 09:43
  • try with `url: "/conv/refresh/uri->segment(3) ?>",` – Saty Jul 07 '15 at 09:47
  • I believe it is not a duplicate post as my config parameters are similar to the ones in the previous question. So I believe it is not the same but related. – Biko Jul 07 '15 at 12:54

2 Answers2

0

Try to change the $config['permitted_uri_chars'] = ''; in config.php file.

Please try it and let me know.

Pratik Soni
  • 2,498
  • 16
  • 26
0

Instead of checking in console errors check Network Tab response for the request

  1. Check you loaded form_validation library and model in before
  2. PHP Lint controller and model files
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Dec 28 '21 at 16:47