Jump to content


Photo

Ajax chat issues.


  • Please log in to reply
22 replies to this topic

#1 tomfmason

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

Posted 25 September 2006 - 08:28 PM

I am not really sure what I am doing wrong here..

Ok I am slowly but surely developing the chat script.

Where to start..??

Ok I will start with the first post issue..

Here is the first version of the js.

//The function below was 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;
}

var http = createRequestObject();
var getText = createRequestObject();
var chatTimer;

function getChat() {
   getText.open('get', 'process.php?action=getChat');
   getText.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   getText.send(null);
   getText.onreadystatechange = handleGetChat;
}

function handleGetChat() {
   if (getText.readystate == 4) {
       var chatText = getText.responseText;
       document.getElementById('chatBox').innerHTML = chatText;
       chatTimer = setTimeout('getChat();', 2000);
   }
}
      
function sendChat() {
   var text = document.getElementById('text').value;
   //this is were the issue began
   http.open('post', 'process.php?action=sendChat');
   http.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
   http.send('text='+text);
   http.onreadystatechange = handleSendChat;
   document.getElementById('text').value = '';
}

function handleSendChat() {
   if (http.readystate == 4) {
       var test = http.responseText;
       if (test == 'empty') {
           document.getElementById('chatBox').innerHTML = 'The text did not get passed';
       } else {
          clearInterval(chatTimer);
          getChat();
       }
   }
}

Here is the process.php

<?php
session_start();
header("Expires: Mon, 26 Jul 1997 05:00:00 GMT" ); 
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");

include("../includes/db.php");
$valid_actions = array('CheckSession', 'startChat', 'getChat', 'sendChat', 'login');  
$action = strip_tags($_GET['action']);
if (!in_array($action, $valid_actions)) {
    echo "invalid action";
    exit();
}
function getaction($action) {
   switch($action) {
       case "sendChat":
            $text = $_POST['text'];
            $name = "Tom";
            if ($text == "") {
	   echo "It did not send the message text";
                exit();
            }	   
            $user_type = "rep";
            $sql = "INSERT INTO `chat_text` (`name`, `user_type`, `text`) 
	           VALUES ('$name', '$user_type', '$text')";
            $res = mysql_query($sql);
        break;
        case "getChat":
	$sql = "SELECT * FROM `text` ORDER BY `text_id` ASC";
	$res = mysql_query($sql);
	$param = "";
	if (mysql_num_rows($res) == 0) {
	    echo "Ready to chat.";
	}else{
	    while ($rw = mysql_fetch_assoc($res)) {
	         $param .= '<b>' . $rw['name'] . '</b>: ' . $rw['text'] . '<br />';
	    }	     	   
	 }
	 echo $param;
         break;
     }
}

getaction($action);
?>

The sendChat case did not send the results to the database . I am not sure if that was just because it was I had it inside of an action or ??

So  I wrote another script called sendchat.php and  changed the sendChat function accordingly. Now it inserts the text correctly but now the getChat function is not working..

Any suggestions as to what I am doing wrong??

Thanks,
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


#2 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 25 September 2006 - 08:34 PM

Can you post a link to the live version?  It's always good to use the JS debugger to find errors.

Info: PHP Manual


#3 tomfmason

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

Posted 25 September 2006 - 08:36 PM

Thanks ober.. I got it sorted out.. I think that the window that I had open had cached the results or something.. I tried it again and it works fine now.

Thanks,
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


#4 tomfmason

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

Posted 26 September 2006 - 04:50 AM

Well I am runing into another issue now. When I have enough messages to fill the chatBox it always displays the message right before the last one here is an example..

Name:   message:
Tom      test
Tom      test2
Tom      test3
tom       test4
Tom      test5

So say test5 is the last message. When I enter another message it displays the message before it and you have to scroll down to see the next message.

I added this is to the getChat case in the process.php

$param .= '<div id="end"></div>';



now I am not realy sure how I can focus the chatBox to the id end. Maybe I am going about this the wrong way..

Any suggestions would be great.

Thanks,
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 tomfmason

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

Posted 26 September 2006 - 08:19 AM

Well I changed

$param .= '<div id="end"></div>';

To
$param .= '<a name="end"></a>';

And in the handleGetChat function I added this.
document.location = '#end';

Well now it reloads to the last message but I have to click on the text box again every time the timeout is reached. That will realy annoy the chatters..lol

I thought maybe I could add something like this.
document.getElementById('text').focus();

This does nothing...

Any suggestions?

Thanks,
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


#6 tomfmason

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

Posted 26 September 2006 - 09:43 AM

Ok I have been thinking, dangerous I know, and I came up with a possible solution. I am not real fond of this one but..

So I guess I could have a frame with the chat box that contains the getchat function..

like I said I am not real fond of this one.. I know that I can make it work but I would rather just solve the current problem without having to use a frame.

Thanks,
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


#7 tomfmason

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

Posted 26 September 2006 - 06:55 PM

I am really beating my head against a wall on this one.. Does anyone have any other suggestions..

I tried the iframe idea and it is not as simple as I thought it was going to be..

I know that there has to be a way of doing this without having to use frames..

Once again, the issue that I am having is that when the page reloads I have to click back on the text area.. This happens every two seconds.. Like I said in a previous post, I tired using document.location = '#end';

Maybe something like
document.getElementById('chatBox').location = "#end";

Would this do the same thing or ??

Any suggestions would be greatly appreciated.

Thanks,
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 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 26 September 2006 - 07:02 PM

Sorry, my JS isn't that good involving manipulating textareas and whatnot.

Info: PHP Manual


#9 tomfmason

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

Posted 26 September 2006 - 07:08 PM

Thats ok. I really appreciate your help anyways. I will figure this out one way or another and when I do I will post the fix..

Thanks again,
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


#10 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 26 September 2006 - 07:13 PM

If nothing else, you could consider posting the chat portion to a div and just grabbing the last 2-300 characters to keep the box minimal.  And if you're worried about people wanting to see the entire history of the chat, you can give them a link to open up the entire conversation in a new window (or just hide a text area with the entire conversation and swap the div for the textarea when they click the link to show history).

There are ways around it if you can't find another good solution.

Info: PHP Manual


#11 tomfmason

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

Posted 26 September 2006 - 08:21 PM

I think that I have figured it out..

Part of the fix is this.

first I defined a new variable in the handleGetChat function.

var chat = document.getElementById('chatBox');

I then added this...

chat.scrollTop = chat.scrollHeight;

I found this when looking at someone else's ajax chat script..

so here is the fix to the handleGetChat function.

function handleGetChat() {
   if (getText.readystate == 4) {
       var chat = document.getElementById('chatBox');
       var chatText = getText.responseText;
       chat.innerHTML = chatText;
       chat.scrollTop = chat.scrollHeight;
       chatTimer = setTimeout('getChat();', 2000);
   }
}

Now I think that I will create another function for when the user scrolls up. I will clearInterval, stop the refresh and then when the user scrolls down I will start it again.

Thanks again ober,
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


#12 tomfmason

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

Posted 26 September 2006 - 08:57 PM

Now I am running into a another issue. I am not sure what would be the best to call the new stopChat function.

which is
function stopChat() {
    clearInterval(chatTimer);
}

I tried this within the chatBox div
<div id="chatBox" onmouseup="stopChat();" onmousedown="restartChat();">

This dose nothing.  I also tried onkeyup and it did nothing.

I am trying to pause the chatTimer when ever the user scrolls up and restart it when they scroll down..

Is this possible?

Thanks,
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


#13 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 26 September 2006 - 10:30 PM

When you say it does nothing, can you verify that the function is called or is it a situation where the timer isn't being disabled?

Info: PHP Manual


#14 tomfmason

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

Posted 26 September 2006 - 10:59 PM

Ok I changed it abit and I got a result(not quite the result that I wanted).

Any ways I changed the chatBox div to this.

<div id="chatBox" onmouseup="javascript:stopChat();" onmousedown="javascript:restartChat();">

Then i changed the stop and restart functions to this(just for testing)

function stopChat() {
    alert('You scrolled up');
}

function restartChat() {
    alert('You scrolled down');
}

Well in IE when I click on the scroll bar I get the message "You scrolled down". Then when I click on the chatBox it's self I get the message that "You scrolled up". Also, dreamweaver says that the onmouseup/down is not supported in Netscape navigator 6.

I am going to try onkeyup/down and see what happens.

Thanks,
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


#15 tomfmason

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

Posted 27 September 2006 - 07:30 AM

@ober

I followed a suggestion from one of your pervious posts and downloaded Opera. I also downloaded FireFox.
I already like FireFox much more then IE..

Now to my current issue.

When I view this script app in Firefox or Opera no results are returned. The messages are sent and I can view them in IE6.

So after a little exploring of the other browsers I found the javascript console in Firefox..

here are the errors that it displayed.

Error: uncaught exception: [Exception... "Component returned failure code: 0x804b000f [nsIXMLHttpRequest.setRequestHeader]"  nsresult: "0x804b000f (<unknown>)"  location: "JS frame :: http://www.thomashos...t/testChat.html :: getChat :: line 44"  data: no]


this repeats four times..

here are some more.

Error: no element found
Source File: http://www.thomashos...action=sendChat
Line: 1, Column: 1
Source Code:
^


repeats 3 times

Error: junk after document element
Source File: http://www.thomashos...?action=getChat
Line: 1, Column: 11
Source Code:
<b>Tom</b>: This is a test message.----------^


repeats 3 times.

The rest are repeats..

Operia had many more. Most were from the css. Also, I removed the stopChat and restartChat functions. I wanted to see if I had basic cross browser functionality. I quess that I do not..

Also, I think that Opera has cached the page. What makes me think this is the fact that I removed all references to the stop and restart functions and it still shows the error requarding these functions.

I am completely lost on this one..lol

Thanks,
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


#16 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 27 September 2006 - 12:44 PM

In Opera: Tools->Preferences->Advanced->Check Documents->Always.  That should make sure that the most up to date version is loaded on a refresh.

I went to http://www.thomashos...t/testChat.html in Opera and your little waiting thing never stops spinning.  What is it waiting for?

Also, I don't think you want to start the timer in your handling function.  You should probably start/stop the timer outside of that.

Info: PHP Manual


#17 tomfmason

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

Posted 27 September 2006 - 08:18 PM

Ok I will will write another function for that.  The reason that the waiting sign never goes away is that I, as you can see, haven't got around to writeing the code for updateing the status yet..

As far as Opera goes. I made the changes that you suggested and now I am not getting any errors(from my script). It is however getting every error from every other site that I visit. You were not jokeing when you said that it was very descriptive..

I am not getting any errors from the chat script and it still does not work for me. It works fine in IE. I haven't tried Firefox since I made some changes..

I am glad that I followed your advise and got Opera. I have several sites that are not cross browser compatible. I have alot of work ahead of me.

Now back to the chat script. Do you think that the timer would have something to do with the results not showing. I am going to change that around right now. They send but do not show up for me (in opera).

Thanks again for all of your help.

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


#18 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 27 September 2006 - 08:33 PM

I'll have a look later tonight.

Info: PHP Manual


#19 tomfmason

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

Posted 28 September 2006 - 08:34 AM

Ha... I got it..

I pulled one of my php debugging tricks. Instead of using echo I use alert..

I found out that it was in the handleGetChat function.

if (getText.readystate == 4) {

readystate should be readyState..lol

It is now working fine in Opera, FireFox and IE 6.

The next issue that I am facing is how to determine if the user as scrolled up.

it refreshes every 2 seconds and sets the srollTop to the scrollHeight.

I have thought about adding a check box like autoscroll or something. Then every time It reloads I will check to see if the auto scroll is checked.. If not then it will not set the scroll top to the scrollHeight.

I am not real fond of that idea.

Or maybe I can have a function like this.


function scrollCheck() {
    var chatBox = document.getElementById('chatBox');
    var top = chatBox.scrollTop
    var height = chatBox.scrollHeight - 150;
    //150 is the height of the chatBox div
    if (top == height) {
       chatBox.scrollTop = chatBox.scrollHeight;
    } else {
       chatBox.scrollTop = top;
    }
}

That should be fine right??

Thanks,
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


#20 ober

ober
  • Staff Alumni
  • Advanced Member
  • 5,337 posts
  • LocationEast Coast, USA

Posted 28 September 2006 - 12:56 PM

Eh... didn't get a chance to look at it last night... sorry.  But at least you got that part working.

If I get some more time later I'll look up some JS references and see what I can find.

Info: PHP Manual





0 user(s) are reading this topic

0 members, 0 guests, 0 anonymous users