PHP

 
Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
User Name:
Password:
Remember me



Go Back   Tutorialized ForumsWeb Design & DevelopmentPHP

Reply
Add This Thread To:
  Del.icio.us   Digg   Google   Spurl   Blink   Furl   Simpy   Y! MyWeb 
Thread Tools Search this Thread Rate Thread Display Modes
 
Unread Tutorialized Forums Sponsor:
  #1  
Old October 6th, 2011, 07:14 AM
mythri hegde mythri hegde is offline
Registered User
Tutorialized Newbie (0 - 499 posts)
 
Join Date: Oct 2011
Posts: 2 mythri hegde User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 26 m 16 sec
Reputation Power: 0
Live Chat for website

I want to integrate LiveChat app to my website. While searching in the net i got a chat app using Ajax.

Here is the code. I have created database and everything is right. But i am not getting how it works i mean how do i add my ids to it and how to know the other person is online.

I will be pasting my code. Please help me.

Chat.html

Code:
<html>
    <head>
        <title>AJAX Driven Web Chat</title>
        <style type="text/css" media="screen">
            .chat_time {
                font-style: italic;
                font-size: 9px;
            }
        </style>
        <script language="JavaScript" type="text/javascript">
            var sendReq = getXmlHttpRequestObject();
            var receiveReq = getXmlHttpRequestObject();
            var lastMessage = 0;
            var mTimer;
            //Function for initializating the page.
            function startChat() {
                //Set the focus to the Message Box.
                document.getElementById('txt_message').focus();
                //Start Recieving Messages.
                getChatText();
            }       
            //Gets the browser specific XmlHttpRequest Object
            function getXmlHttpRequestObject() {
                if (window.XMLHttpRequest) {
                    return new XMLHttpRequest();
                } else if(window.ActiveXObject) {
                    return new ActiveXObject("Microsoft.XMLHTTP");
                } else {
                    document.getElementById('p_status').innerHTML = 'Status: Cound not create XmlHttpRequest Object.  Consider upgrading your browser.';
                }
            }

            //Gets the current messages from the server
            function getChatText() {
                if (receiveReq.readyState == 4 || receiveReq.readyState == 0) {
                    receiveReq.open("GET", 'getChat.php?chat=1&last=' + lastMessage, true);
                    receiveReq.onreadystatechange = handleReceiveChat; 
                    receiveReq.send(null);
                }           
            }
            //Add a message to the chat server.
            function sendChatText() {
                if(document.getElementById('txt_message').value == '') {
                    alert("You have not entered a message");
                    return;
                }
                if (sendReq.readyState == 4 || sendReq.readyState == 0) {
                    sendReq.open("POST", 'getChat.php?chat=1&last=' + lastMessage, true);
                    sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    sendReq.onreadystatechange = handleSendChat; 
                    var param = 'message=' + document.getElementById('txt_message').value;
                    param += '&name=User1';
                    param += '&chat=1';
                    sendReq.send(param);
                    document.getElementById('txt_message').value = '';
                }                           
            }
            //When our message has been sent, update our page.
            function handleSendChat() {
                //Clear out the existing timer so we don't have 
                //multiple timer instances running.
                clearInterval(mTimer);
                getChatText();
            }
            //Function for handling the return of chat text
            function handleReceiveChat() {
                if (receiveReq.readyState == 4) {
                    var chat_div = document.getElementById('div_chat');
                    var xmldoc = receiveReq.responseXML;
                    var message_nodes = xmldoc.getElementsByTagName("message"); 
                    var n_messages = message_nodes.length
                    for (i = 0; i < n_messages; i++) {
                        var user_node = message_nodes[i].getElementsByTagName("user");
                        var text_node = message_nodes[i].getElementsByTagName("text");
                        var time_node = message_nodes[i].getElementsByTagName("time");
                        chat_div.innerHTML += user_node[0].firstChild.nodeValue + '&nbsp;';
                        chat_div.innerHTML += '<font class="chat_time">' + time_node[0].firstChild.nodeValue + '</font><br />';
                        chat_div.innerHTML += text_node[0].firstChild.nodeValue + '<br />';
                        chat_div.scrollTop = chat_div.scrollHeight;
                        lastMessage = (message_nodes[i].getAttribute('id'));
                    }
                    mTimer = setTimeout('getChatText();',2000); //Refresh our chat in 2 seconds
                }
            }
            //This functions handles when the user presses enter.  Instead of submitting the form, we
            //send a new message to the server and return false.
            function blockSubmit() {
                sendChatText();
                return false;
            }
            //This cleans out the database so we can start a new chat session.
            function resetChat() {
                if (sendReq.readyState == 4 || sendReq.readyState == 0) {
                    sendReq.open("POST", 'getChat.php?chat=1&last=' + lastMessage, true);
                    sendReq.setRequestHeader('Content-Type','application/x-www-form-urlencoded');
                    sendReq.onreadystatechange = handleResetChat; 
                    var param = 'action=reset';
                    sendReq.send(param);
                    document.getElementById('txt_message').value = '';
                }                           
            }
            //This function handles the response after the page has been refreshed.
            function handleResetChat() {
                document.getElementById('div_chat').innerHTML = '';
                getChatText();
            }   
        </script>
    </head>
    <body onLoad="javascript:startChat();">
        <h2><a href="http://www.dynamicAJAX.com" style="color: #000000; text-decoration: none;">AJAX Driven Web Chat</a></h2>
        <p id="p_status">Status: Normal</p>
        Current Chitter-Chatter:
        <div id="div_chat" style="height: 300px; width: 500px; overflow: auto; background-color: #CCCCCC; border: 1px solid #555555;">

        </div>
        <form id="frmmain" name="frmmain" onSubmit="return blockSubmit();">
            <input type="button" name="btn_get_chat" id="btn_get_chat" value="Refresh Chat" onClick="javascript:getChatText();" />
            <input type="button" name="btn_reset_chat" id="btn_reset_chat" value="Reset Chat" onClick="javascript:resetChat();" /><br />
            <input type="text" id="txt_message" name="txt_message" style="width: 447px;" />
            <input type="button" name="btn_send_chat" id="btn_send_chat" value="Send" onClick="javascript:sendChatText();" />
        </form>
    </body>

</html>


getChat.php

Code:
header("Last-Modified: " . gmdate( "D, d M Y H:i:s" ) . "GMT" ); 
header("Cache-Control: no-cache, must-revalidate" ); 
header("Pragma: no-cache" );
header("Content-Type: text/xml; charset=utf-8");

require('database.php');

//Check to see if a message was sent.
if(isset($_POST['message']) && $_POST['message'] != '') {
    $sql = "INSERT INTO message(chat_id, user_id, user_name, message, post_time) VALUES (" . 
            db_input($_GET['chat']) . ", 1, '" . db_input($_POST['name']) . 
            "', '" . db_input($_POST['message']) . "', NOW())";
    db_query($sql);
}
//Check to see if a reset request was sent.
if(isset($_POST['action']) && $_POST['action'] == 'reset') {
    $sql = "DELETE FROM message WHERE chat_id = " . db_input($_GET['chat']);
    db_query($sql);
}

//Create the XML response.
$xml = '<?xml version="1.0" ?><root>';
//Check to ensure the user is in a chat room.
if(!isset($_GET['chat'])) {
    $xml .='Your are not currently in a chat session.  <a href="">Enter a chat session here</a>';
    $xml .= '<message id="0">';
    $xml .= '<user>Admin</user>';
    $xml .= '<text>Your are not currently in a chat session.  <a href="">Enter a chat session here</a></text>';
    $xml .= '<time>' . date('h:i') . '</time>';
    $xml .= '</message>';
} else {
    $last = (isset($_GET['last']) && $_GET['last'] != '') ? $_GET['last'] : 0;
    $sql = "SELECT message_id, user_name, message, date_format(post_time, '%h:%i') as post_time" . 
        " FROM message WHERE chat_id = " . db_input($_GET['chat']) . " AND message_id > " . $last;
    $message_query = db_query($sql);
    //Loop through each message and create an XML message node for each.
    while($message_array = db_fetch_array($message_query)) {
        $xml .= '<message id="' . $message_array['message_id'] . '">';
        $xml .= '<user>' . htmlspecialchars($message_array['user_name']) . '</user>';
        $xml .= '<text>' . htmlspecialchars($message_array['message']) . '</text>';
        $xml .= '<time>' . $message_array['post_time'] . '</time>';
        $xml .= '</message>';
    }
}
$xml .= '</root>';
echo $xml;
?>


database.php

Code:
db_connect() or die('Unable to connect to database server!');


  function db_connect($server = 'localhost', $username = 'livechat', $password = 'password', $database = 'dbase', $link = 'db_link') {
    global $$link;

    $$link = mysql_connect($server, $username, $password);

    if ($$link) mysql_select_db($database);

    return $$link;
  }

  function db_error($query, $errno, $error) { 
    die('<font color="#000000"><b>' . $errno . ' - ' . $error . '<br><br>' . $query . '<br><br><small><font color="#ff0000">[STOP]</font></small><br><br></b></font>');
  }

  function db_query($query, $link = 'db_link') {
    global $$link;

    $result = mysql_query($query, $$link) or db_error($query, mysql_errno(), mysql_error());

    return $result;
  }
//Get a row from the database query
  function db_fetch_array($db_query) {
    return mysql_fetch_array($db_query, MYSQL_ASSOC);
  }
//The the number of rows returned from the query.
  function db_num_rows($db_query) {
    return mysql_num_rows($db_query);
  }
//Get the last auto_increment ID.
  function db_insert_id() {
    return mysql_insert_id();
  }
//Add HTML character incoding to strings
  function db_output($string) {
    return htmlspecialchars($string);
  }
//Add slashes to incoming data
  function db_input($string, $link = 'db_link') {
    global $$link;

    if (function_exists('mysql_real_escape_string')) {
      return mysql_real_escape_string($string, $$link);
    } elseif (function_exists('mysql_escape_string')) {
      return mysql_escape_string($string);
    }

    return addslashes($string);
  }


and i have two tables
chat

Code:
CREATE TABLE `chat` (
  `chat_id` INT(11) NOT NULL AUTO_INCREMENT,
  `chat_name` VARCHAR(64) DEFAULT NULL,
  `start_time` DATETIME DEFAULT NULL,
  PRIMARY KEY  (`chat_id`)
) ENGINE=INNODB DEFAULT CHARSET=latin1;


message
Code:
CREATE TABLE `message` (
  `message_id` INT(11) NOT NULL AUTO_INCREMENT,
  `chat_id` INT(11) NOT NULL DEFAULT '0',
  `user_id` INT(11) NOT NULL DEFAULT '0',
  `user_name` VARCHAR(64) DEFAULT NULL,
  `message` TEXT,
  `post_time` DATETIME DEFAULT NULL,
  PRIMARY KEY  (`message_id`)



please help me how do i know which user is online. And which technloy i need to use. please help me

Reply With Quote
  #2  
Old October 6th, 2011, 01:58 PM
mythri hegde mythri hegde is offline
Registered User
Tutorialized Newbie (0 - 499 posts)
 
Join Date: Oct 2011
Posts: 2 mythri hegde User rank is Just a Lowly Private (1 - 20 Reputation Level) 
Time spent in forums: 26 m 16 sec
Reputation Power: 0
Please somebody can help me in this?

Reply With Quote
Reply

Viewing: Tutorialized ForumsWeb Design & DevelopmentPHP > Live Chat for website


Developer Shed Advertisers and Affiliates


Thread Tools  Search this Thread 
Search this Thread:

Advanced Search
Display Modes  Rate This Thread 
Rate This Thread:


Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
View Your Warnings | New Posts | Latest News | Latest Threads | Shoutbox
Forum Jump


Forums: » Register « |  User CP |  Games |  Calendar |  Members |  FAQs |  Sitemap |  Support | 
  
 

Powered by: vBulletin Version 3.0.5
Copyright ©2000 - 2017, Jelsoft Enterprises Ltd.

© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap