Jump to content


Photo

LIVE CHAT???????Any one please help me?


  • Please log in to reply
19 replies to this topic

#1 rajmohan

rajmohan
  • Members
  • PipPipPip
  • Advanced Member
  • 169 posts

Posted 10 October 2006 - 04:24 AM

Hai guys,


i am having few experience to do projects in php/Mysql but now i am in trouble because my new project came with LIVE CHAT i dont know how to do ? Can any one give me a code or

tell me where i can collect the code please i think it wiil take too much time right? guide me please waiting for your results.

#2 Ninjakreborn

Ninjakreborn
  • Members
  • PipPipPip
  • Information Technology Specialist
  • 3,922 posts
  • Age:33

Posted 10 October 2006 - 04:28 AM

Live chat can be programming in php a little but not like your thinking, it's going to be something else, like java, perl, c languages, or something a cgi bin or plugin.
http://www.boutell.c...ng/support.html

------

Business Website: http://www.infotechnologist.biz

Personal Website: http://www.joyelpuryear.com

Blog Site: http://www.realmofwriting.com
Services: Web development, application development, mobile development, and custom development. All services listed on my website.


#3 rajmohan

rajmohan
  • Members
  • PipPipPip
  • Advanced Member
  • 169 posts

Posted 10 October 2006 - 04:32 AM

i your point of view it is easy man for me this is the first time i am doing this i dont know how to start please tell me how to do it. you have coding for that

#4 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 10 October 2006 - 04:36 AM

I created a live support script that uses php and ajax.  It is not finished or I would post some code for you.. I would recomend that you use a third party script until you get more familar with php and maybe something like javascript(Ajax). A decent chat script is a farily complicated undertaking.

Good Luck,
Tom

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#5 rajmohan

rajmohan
  • Members
  • PipPipPip
  • Advanced Member
  • 169 posts

Posted 10 October 2006 - 04:42 AM

can you tell me how to do in simple way. is there any options you have.

#6 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 10 October 2006 - 05:06 AM

Ok I will write you a very very simple chat script tutorial. It will come with basicly no features other then a login.

It will take me a little bit so be patient.

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#7 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 10 October 2006 - 12:06 PM

ok where to start... I guess I will start with what you will need in the database. Like I said this is going to be very simple. You will need two tables.


Here is the sql for the first table called chatSessions

CREATE TABLE `chatSessions` (
`chat_id` INT NOT NULL AUTO_INCREMENT ,
`session_id` VARCHAR( 33 ) NOT NULL ,
`nick` VARCHAR( 25 ) NOT NULL ,
`start_time` TIMESTAMP NOT NULL ,
PRIMARY KEY ( `chat_id` )
) TYPE = MYISAM ;

And here is the sql for the second table called chatText

CREATE TABLE `chatText` (
`text_id` INT NOT NULL AUTO_INCREMENT ,
`nick` VARCHAR( 25 ) NOT NULL ,
`text` VARCHAR( 500 ) NOT NULL ,
`chatDate` VARCHAR( 10 ) NOT NULL ,
`chatTime` VARCHAR( 10 ) NOT NULL ,
PRIMARY KEY ( `text_id` )
) TYPE = MYISAM ;


Now we move on to the back end php script.

I will explain it as I go.

<?php
session_start();//start the session
include("db.php");//your database connection file

//now we create an array with valid actions.
$valid_actions = array('login', 'sendChat', 'sessionCheck', 'getChat');
//now we check the action to see if it matches our array.

$action = strip_tags($_GET['action']);

if (!in_array($action, $valid_actions)) {
    //if the action dosn't match then we stop the script
    die("invalid action");
}

function getaction($action) {
    switch($action) {
        case "login":
              $nick = mysql_real_escape_string(strip_tags($_POST['nick']));
              $session_id = session_id();
              if ($nick == '') {
                  //I know that this seems simple but you will see why I only echoed 'empty' later in the script
                  echo "empty";
              }
              $sql = "INSERT INTO `chatSessions` (`session_id`, `nick`) VALUES ('$session_id', '$nick')";
              $res = mysql_query($sql);
              if (!$res) {
                  echo "error";
                  exit();
              } else {
                  $_SESSION['nick'] = $nick;
                  //we will use this later to make sure that we do not get any chat messages that were entered before the user logged in
                  $_SESSION['chatDate'] = date('Y-m-d');
                  $_SESSION['chatTime'] = date('Gi');
              }
        break;
        case "sendChat":
              $text = mysql_real_escape_string(strip_tags($_POST['text']));
              $nick = $_SESSION['nick'];
              $chatDate = date('Y-m-d');
              $chatTime = date('Gi');
              $sql = "INSERT INTO `chatText` (`nick`, `text`, `chatDate`, `chatTime`) 
                        VALUES ('$nick', '$text', '$chatDate', '$chatTime')";
              $res = mysql_query($sql) or die(mysql_error());;
              if (!$res) {
                  echo "error";
              }
        break;
        case "getChat":
              $chatDate = $_SESSION['chatDate'];
              $chatTime = $_SESSION['chatTime'];
              $sql = "SELECT * FROM `chatText` WHERE `chatDate` = '$chatDate'";
              $res = mysql_query($sql);
	  if (mysql_num_rows($res) < 1) {
	      echo "Ready to chat";
	 }	  
              if (!$res) {
                  echo "error";
                  exit();
              }
              while ($rw = mysql_fetch_assoc($res)) {
                       //now this will only echo the messages that were entered at the same time or after the user logged in.
                      if ($rw['chatTime'] >= $chatTime) {
                          echo '<b>' . $rw['nick'] . '</b> ' . $rw['text'] . '<br />';
                      }
              }
        break;
        case "sessionCheck":
               if (!$_SESSION['nick']) {
                   echo '
    <form action="#" onsubmit="return loginSubmit();">
     Please choose a nick name<br />
     <input type="text" id="nick" />
     <div id="loginButton"><input type="button" onclick="login();" value="Login"/></div>
    </form>';
               } else {
                   echo "logged";
               }
        break;
   }
}

//now this will call the getaction function.
getaction($action);
?>



Now we will move to the html. Here is the simple css for this script. You can change this around to fit you page.

h1{
  font-family: Tahoma;
  color: #000000;
  font-size:16px;
  font-weight: bold;
}
  
#main{
   width: 500px;
   margin: 0px auto;
   padding: 0px;
   background-color: #CDCDCD;
   float: left;
   overflow: hidden;
   border: 2px solid #555555;
}

#content{
   float: left;
   width: 420px;
   background-color: #CCCCCC;
   padding: 0px 0px 0px 40px;
}

#chatBox{
   width: 418px;
   height: 150px;
   background-color:#FFFFFF;
   /*This will allow us to scroll up and down with in the chatBox div*/ 
   overflow: auto;
   border: 1px solid #555555;
   padding: 0px 0px 0px 0px;
   font-family: Tahoma;
   font-size: 14px;
   font-weight: normal;
}

#form{
   width: 100%;
   padding: 10px 0px 0px 0px;
}

#button{
   padding: 0px 0px 0px 0px;
   float:right;
}

Now we are on to the Javascript(Ajax)

function startChat() {
   sessionCheck();
   document.getElementById('text').focus;
   getChat();
}

//this creates a XMLHTTP instance. Provided by ober.
function createRequestObject() {
    if (window.XMLHttpRequest) { // Mozilla, Safari, Opera...
        var xmlhttp = new XMLHttpRequest();
        if (xmlhttp.overrideMimeType)
	    xmlhttp.overrideMimeType('text/xml');
    }
	else if (window.ActiveXObject) { // IE
        try {
            var xmlhttp = new ActiveXObject("Msxml2.XMLHTTP");
        } catch (e) {
            try {
                var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            } catch (e) {}
        }
    }

    if (!xmlhttp) {
        alert('Giving up :( Cannot create an XMLHTTP instance');
        return false;
    }
    return xmlhttp;
}

//these variables will be used later on in the script
var sendReq = createRequestObject();
var recieveReq = createRequestObject();
var sess = createRequestObject();
var http = createRequestObject();
//we declare the chatTimer variable
var chatTimer;

function sessionCheck() {
   //this opens the php file in the get method
   sess.open('GET', 'chatTutorial.php?action=sessionCheck');
   //we are not sending anything to the php file so we do the following
   sess.send(null);
   // now we send the results to another function
   sess.onreadystatechange = handleSessionCheck;
}

function handleSessionCheck() {
   if (sess.readyState == 4) {
       //the response from our script
       var response = sess.responseText;
       if (response == 'logged') {
	   //if the user is loggedin then we call the get chat function
	   getChat();
       } else {
	    // if the user is not logged in then we will show the login form.
	    document.getElementById('form').innerHTML = response;
       }
   }
}

function login() {
   //this is how we get the imputed data from the text field
   var nick = document.getElementById('nick').value;
   if (nick == '') {
       alert('You must enter a nick name to enter the chat');
   } else {
      //now we open the php file in the post method
      http.open('POST', 'chatTutorial.php?action=login');
      //now we set a request header
      http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
      //now we send the nick name to the php file
      http.send('nick=' + nick);
      http.onreadystatechange = handleLogin;
   }
}

function handleLogin() {
   if (http.readyState == 4) {
       var response = http.responseText;
       if ((response == 'empty') || (response == 'error')) {
	    if (response == 'empty') {
		alert('You must enter a nick name to join the chat');
	    } else if (response == 'error') {
		alert('There was an error. Please contact the web master');
	    }
       } else {
	    getChat();
       }
    }
}

//now the get chat function
function getChat() {
   //now we open the php file and get the chat messages entered after the user has loged in
   recieveReq.open('GET', 'chatTutorial.php?action=getChat');
   recieveReq.send(null);
   recieveReq.onreadystatechange = handleGetChat;
}

function handleGetChat() {
   if (recieveReq.readyState == 4) {
       var response = recieveReq.responseText;
       if (response == 'error') {
	   alert('There was an error is retrieving the messages. Please contact the webmaster');
       } else {
	   //this will check to see if the user has scrolled up or not
	   var check = scrollCheck();
	   var chat = document.getElementById('chatBox');
	   if (check == true) {
               //if have not scrolled up then we set the top of the scroll box to the height of the scroll box
               chat.innerHTML = response;
	       chat.scrollTop = chat.scrollHeight;
	  } else {
	      //if the user has scrolled up we do not move the scroll box down untill they scroll down again	    
	      //now we write the chat to the chat box div.
	     chat.innerHTML = response;
	  }	 
	  //now we set a timmer to check for new messages every two seconds.
	  chatTimer = setTimeout('getChat();', 2000);
       }
    }
}

//this is the scroll check function. This will tell us if the user has scrolled up or not
function scrollCheck() {
   var chatBox = document.getElementById('chatBox');
   var top = chatBox.scrollTop;
   //150 is the height of the div chat box
   var height = chatBox.scrollHeight - 150;
   //in FireFox when you subtract the scroll Top from the scroll height the value is -86
   //and sometimes if the user has entered a message the just fills one line the chat scroll height will
   //be less then 5. This took me a while to figure out.
   if ((top == height) || ((height - top) < 5) ||(height < 20)) {
       return true;
   } else {
       return false;
   }
}   	   	   

//now we send the chat.
function sendChat() {
    var text = document.getElementById('text').value;
    //now we open the php file for posting.
    sendReq.open('POST', 'chatTutorial.php?action=sendChat');
    //now we set up a request header
    sendReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    //now we send the results from the text input to the php file
    sendReq.send('text=' + text);
    sendReq.onreadystatechange = handleSendChat;
}

function handleSendChat() {
    if (sendReq.readyState == 4) {
	var chatBox = document.getElementById('chatBox');
        var response = sendReq.responseText;
	if (response == 'error') {
	   alert('There was an error in sending your message. Please contact the webmaster.');
        } else {
	   //now we clear the chat timmer		
	   clearInterval(chatTimer);
	   document.getElementById('text').value = '';
	   chatBox.scrollTop = chatBox.scrollHeight;
	   getChat();
	}		
    }
}

//now this is the block submit function. If the user hits enter instead of clicking on the send button
//you will see the text in the address bar of your browser. This function will prevent that.

function blockSubmit() {
   sendChat()
   //this is the part that keeps the results from showing in the address bar.
   return false;
}

//this is basicly the same as the blockSubmit function. This is for the login form
function loginSubmit() {
   login();
   return false;
}

Here is the html for my example. minus the script tags and the link to the style sheet.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Ajax Chat Tutorial</title>
<!--Place the link to the style sheet and the javascript here-->
<body onload="sessionCheck();">
<div id="main">
 <div id="content">
   <h1>Ajax chat </h1>
  <div id="chatBox">
  </div>
  <div id="form">
   <form action="#" onsubmit="return blockSubmit();">
    <textarea id="text" cols="50" rows="2"></textarea>
	<div id="button"><input type="button" onclick="sendChat();" value="Send" /></div>
   </form>
  </div>
 </div>
</div>
</body>
</html>

I have attached the chatTutorial.html and the chatTutorial.php. Both are working fine.. Also, here is a link to a live version http://www.thomashos...atTutorial.html . I am only going to leave this up for a few days.

Hope that helps,
Tom

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#8 rajmohan

rajmohan
  • Members
  • PipPipPip
  • Advanced Member
  • 169 posts

Posted 10 October 2006 - 12:09 PM

ok TOM i will try this one. few min. please

#9 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 10 October 2006 - 12:25 PM

Here's a very good Ajax IM solution....

http://www.unwieldy.net/ajaxim/

You can even try it out when you get there, although it's less of a chat engine and more of a messenger engine.

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#10 Gruzin

Gruzin
  • Members
  • PipPipPip
  • Advanced Member
  • 448 posts
  • LocationGeorgia

Posted 10 October 2006 - 12:59 PM

Hi Tom,
I've tryed your script and I get this error:

Warning: mysql_num_rows(): supplied argument is not a valid MySQL result resource in /users/3d_cn~1/html/test/chatTutorial.php on line 54
emptyerror

Any idea how to fix that?
thanks,
George
I don't need your script, I'll try to write it myself

#11 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 10 October 2006 - 01:05 PM

Change this on line 52...
$sql = "SELECT * FROM `chattext` WHERE `chatDate` = '$chatDate'";

To this:
$sql = "SELECT * FROM `chatText` WHERE `chatDate` = '$chatDate'";

I believe there's a case-sensitivity issue... You'll also need to change line 42 from chattext to chatText

Regards
Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#12 Gruzin

Gruzin
  • Members
  • PipPipPip
  • Advanced Member
  • 448 posts
  • LocationGeorgia

Posted 10 October 2006 - 01:08 PM

Thanks Huggie,
But now the textfield displays only "emty"... I don't get it  :-\ does it mean that someone else should be loged in to send the message?

George
I don't need your script, I'll try to write it myself

#13 HuggieBear

HuggieBear
  • Members
  • PipPipPip
  • Advanced Member
  • 1,899 posts
  • LocationEngland, UK

Posted 10 October 2006 - 01:10 PM

I've amended my previous post too, as there's another change to make.

Huggie
Advice to MySQL users: Get phpMyAdmin and test your queries work there first, take half the hassle out of diagnosis, also check the reserved words list.

Links: PHP Docs :: RegEx's :: MySQL :: DevGuru :: w3schools

#14 Gruzin

Gruzin
  • Members
  • PipPipPip
  • Advanced Member
  • 448 posts
  • LocationGeorgia

Posted 10 October 2006 - 01:14 PM

Well, I've done that, but still the same  :)
Here you go:
http://3d.caucasus.net/test

Hope we can solve this kind of a simple problem :)

Regards,
George
I don't need your script, I'll try to write it myself

#15 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 10 October 2006 - 06:56 PM

Change this on line 52...

$sql = "SELECT * FROM `chattext` WHERE `chatDate` = '$chatDate'";

To this:
$sql = "SELECT * FROM `chatText` WHERE `chatDate` = '$chatDate'";

I believe there's a case-sensitivity issue... You'll also need to change line 42 from chattext to chatText

Regards
Huggie

I've amended my previous post too, as there's another change to make.

Huggie


Thanks Huggie.

I fixed it on the script that I have but not here..lol Forgot to. I had been up almost all night.

Thanks Huggie,
But now the textfield displays only "emty"... I don't get it  :-\ does it mean that someone else should be loged in to send the message?

George


Now that is rather simple to change that. You can do this by changing the following line

line 55.
change
echo "empty";
to what ever you want..

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#16 rajmohan

rajmohan
  • Members
  • PipPipPip
  • Advanced Member
  • 169 posts

Posted 11 October 2006 - 09:58 AM

sorry to say this guys,

actually i put all the files and saved as chat.php and create a table for both chatSession and chatText but it is not working i got a error  like this

Warning: Undefined index: action in E:\mohan\Oct06\11Oct06\navo\chat.php on line 8
invalid action

#17 rajmohan

rajmohan
  • Members
  • PipPipPip
  • Advanced Member
  • 169 posts

Posted 11 October 2006 - 12:06 PM

Help please i have a problem in executing this one it

#18 tomfmason

tomfmason
  • Staff Alumni
  • Advanced Member
  • 1,696 posts
  • Locationstealing your wifi

Posted 11 October 2006 - 01:02 PM

Ok are you trying to access the php processing file directly? That is the only reason that I can see that error popping up. Have a look at my source code at the link that I provided. The user never actually sees the php file. That is all handled with javascript(Ajax).

I have been up all night trying to finish a project so I will post a complete fix to my script in about 8 hours.. (after I get some sleep)

Tom

Traveling East in search of instruction, and West to propagate the knowledge I have had gained.

current projects: pokersource

My Blog | My Pastebin | PHP Validation class | Backtrack linux


#19 rajmohan

rajmohan
  • Members
  • PipPipPip
  • Advanced Member
  • 169 posts

Posted 14 October 2006 - 05:59 AM

yes it is working but i received error in this line

if (!$_SESSION['nick'])

error is
Warning: Undefined index: nick in E:\mohan\Oct06\14Oct06\navo\chatTutorial.php on line 69

i changed it as

if(!isset($_SESSION['nick'])

error is gone but after entering the name i click Login button but there is no reaction what is the reason

please tell me


#20 Ninjakreborn

Ninjakreborn
  • Members
  • PipPipPip
  • Information Technology Specialist
  • 3,922 posts
  • Age:33

Posted 17 October 2006 - 05:43 PM

Ok no offence, but this was rather sad.

You needed help and tom set here and created you an entire damn application, took him well over 6-9 hours.  For free at that, and you didn't even say thanks to him once, I read this whole thread 3-4 times to make sure I wasn't wrong, you should have atleast said thank you towards him for building it for you.

------

Business Website: http://www.infotechnologist.biz

Personal Website: http://www.joyelpuryear.com

Blog Site: http://www.realmofwriting.com
Services: Web development, application development, mobile development, and custom development. All services listed on my website.





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users