Monday, February 23, 2015

Aplikasi Chat dengan Codeigniter

Bagikan ke :

Selamat Malam sob, disini saya berbagi ilmu tentang codeigniter, kali ini saya membuat sebuah aplikasi chat sederhana menggunakan framework codeigniter.

Pertama buat file chat.php di folder application/controller
Sourc code

<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

class Chat extends CI_Controller {
  
  public function index() {       
    $this->load->view('chat-view');
  }
  
  public function get_chats() {
    /* application/config/database.php */
    $dbconnect = $this->load->database();
    
    /* memanggil model
    /application/models/file.php */
    $this->load->model('Chat_model');
    
 
    $this->Chat_model->create_table();
    
    echo json_encode($this->Chat_model->get_chat_after($_REQUEST["time"]));
  }
  
  public function insert_chat() {

    /* application/config/database.php */
    $dbconnect = $this->load->database();
    

    $this->load->model('Chat_model');
    

    $this->Chat_model->create_table();

    $this->Chat_model->insert_message($_REQUEST["message"]); 
  }
  
  public function time() {
    echo "[{\"time\":" +  time() + "}]";
  }
  
}?>

Kedua buat file chat_model.php di folder application/model

<?php

class Chat_model extends CI_Model {
  
  function __construct() 
  {

    parent::__construct();
  }
function get_last_item()
  {
    $this->db->order_by('id', 'DESC');
    $query = $this->db->get('Chats', 1);
    return $query->result();
  } 
   function insert_message($message)
  {
    $this->message = $message;
    $this-> time = time();  
    $this->db->insert('Chats', $this);
  }
  function get_chat_after($time)
  {
    $this->db->where('time >', $time)->order_by('time', 'DESC')->limit(10); 
    $query = $this->db->get('Chats');  
    $results = array();
      foreach ($query->result() as $row)
    {
      $results[] = array($row->message,$row->time);
    }
    return array_reverse($results);
  }
  function create_table()
  { 
    $this->load->dbforge();
    $fields = array(
                    'id' => array(
                                  'type' => 'INT',
                                  'constraint' => 5,
                                  'unsigned' => TRUE,
                                  'auto_increment' => TRUE
                              ),
                    'message' => array(
                                  'type' => 'TEXT'
                              ),
                    'time' => array(
                        'type' => 'INT'
                    )
              );
    $this->dbforge->add_field($fields);
      $this->dbforge->add_key('id', TRUE);
       $this->dbforge->create_table('Chats', TRUE);
  }
} 
 

Terakhir buat tampilan chat-view.php di folder application/views
 <html>
<head>
  <title> Chat Exmaples! </title>
  <script src="//ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
  <script> 
    var time = 0;
  
    var updateTime = function (cb) {
      $.getJSON("index.php/chat/time", function (data) {
          cb(~~data);
      });
    };
    
    var sendChat = function (message, cb) {
      $.getJSON("index.php/chat/insert_chat?message=" + message, function (data){
        cb();
      });
    }
    
    var addDataToReceived = function (arrayOfData) {
      arrayOfData.forEach(function (data) {
        $("#received").val($("#received").val() + "\n" + data[0]);
      });
    }
    
    var getNewChats = function () {
      $.getJSON("index.php/chat/get_chats?time=" + time, function (data){
        addDataToReceived(data);
        // reset scroll height
        setTimeout(function(){
           $('#received').scrollTop($('#received')[0].scrollHeight);
        }, 0);
        time = data[data.length-1][1];
      });      
    }
     $( document ).ready ( function () {
      // set an on click on the button
      $("form").submit(function (evt) {
        evt.preventDefault();
        var data = $("#text").val();
        $("#text").val('');
        // get the time if clicked via a ajax get queury
        sendChat(data, function (){
          alert("dane");
        });
      });
      setInterval(function (){
        getNewChats(0);
      },1500);
    });
    
  </script>
</head>
<body>
  <h1> Contoh Chat dengan Codeigniter </h1>
  
  <textarea id="received" rows="10" cols="50">
  </textarea>
  <form>
    <input id="text" type="text" name="user">
    <input type="submit" value="Send">
  </form>
</body>
</html>

Ini Hasilnya Gan, Contoh Chat dengan Codeigniter



Eko Saputro

Saya ini cuma Mahasiswa Informatika Biasa yang amburadul dan masih sangat jauh dari kata sempurna. Selain itu juga Tidak Puas dengan Keadilan Kampus. Tapi tetep semangat dan saya yakin kesuksesan tidak dengan IPK (alasan lama).

3 comments: