Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations strongm on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

Chat Quest2 1

Status
Not open for further replies.

MAWarGod

Programmer
Feb 15, 2002
352
US
the other day I was searching for a examples and I came across a old thread I started trying to make a chat script..


The thread was closed so I couldn't ask My question there..
in the thread jpadie shared a script with me..
ChatRoomServer.php
Code:
<?php
$chat = new chats;

class chats{

    private $timestamp = 0;
    private $action;
    
    function chats(){

        $this->timestamp = time();
        $dbserver = mysql_connect('localhost', 'mychat', 'mychat') or die('error');
@mysql_select_db('mychat',$dbserver) or die('error');
        $result = mysql_query("SHOW TABLES LIKE 'chat'");
        if (mysql_num_rows($result) === 0){
            $this->createDatabaseSchema();
        }
        $this->action = isset($_POST['action']) ? $_POST['action'] : 'getChatData';
        $this->switchBoard();
    }
    
    function switchBoard(){
        switch ($this->action){
            case 'writeChatData':
                if ($this->writeChatData()){
                    echo '1';
                } else {
                    echo '0';
;                }
            break;
            default:
                echo $this->getChatData();
        }    
    }
    
    function getChatData(){
        $return ='';
        $timestamp = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
        if ($timestamp == 'null') $timestamp = 0;
        $query = "Select chatID, chatPerson, chatTimestamp, chatText from chat where chatTimestamp > ? order by chatTimestamp DESC limit 50 ";
        $stmnt = $this->pdo->prepare($query);
        $stmnt->execute(array($timestamp));
        $chats = $stmnt->fetchAll();
        foreach ($chats as $chat){
            $date = date('Y-m-d H:i:s', $chat['chatTimestamp']);
            $chatText = nl2br($chat['chatText']);
            $return .= <<<HTML
<tr>
    <td id="{$chat['chatID']}">{$chat['chatPerson']}<br/>$date</td>
    <td>{$chatText}</td>
</tr>
HTML;
        }
        if (empty($return)){
            return 'none';
        } else {
            return json_encode(array('timestamp'=>$this->timestamp,'chatText'=>$return));
        }
    }
    
    function writeChatData(){
        $chatPerson = empty($_POST['chatPerson']) ? NULL : trim($_POST['chatPerson']);
        $chatText = empty($_POST['chatText']) ? NULL : trim($_POST['chatText']);
        if (empty($chatText) || empty($chatPerson)){
            return false;
        } else {
            if (get_magic_quotes_gpc()){
                $chatPerson = stripslashes($chatPerson);
                $chatText = stripslashes($chatText);
            }
            $query = "Insert into chat (chatTimestamp, chatPerson, chatText) values (?,?,?)";
            $stmnt = $this->pdo->prepare($query);
            if ($stmnt){
                $stmnt->execute(array(time(), $chatPerson, $chatText));
            } else {
                print_r($this->pdo->errorInfo());
            }
            if ($stmnt !== false){
                return true;
            } else {
                return false;
            }
        }
    }
    
    function createDatabaseSchema(){
        $query = "    create table 
                    chat
                    (
                    chatID integer NOT NULL PRIMARY KEY AUTOINCREMENT,
                    chatTimestamp integer NOT NULL,
                    chatPerson text NOT NULL,
                    chatText varchar NOT NULL
                    )";
        $this->pdo->exec($query);
    }
}
?>
ChatRoomServer.js
Code:
var timer = null;
var chatTable;
var timestamp = null;
var xo = null;
var url = 'chatRoomServer.php';

function createObject(){
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        xo = new ActiveXObject("Microsoft.XMLHTTP");
    }else{
        xo = new XMLHttpRequest();
    }
    
}
function updateChatRoom(){
    if (!xo) {createObject();}
    xo.onreadystatechange = function () {
            if (xo.readyState == 4) {
                if (xo.status == 200) {
                    if(xo.responseText == 'none'){
                        //do nothing
                    } else {
                        var rObj = eval('(' + xo.responseText + ')');
                        timestamp = rObj.timestamp;
                        //console.log('timestamp is '+ timestamp);
                        displayUpdatedChats(rObj.chatText)
                    }
                }
            }
        };
    try {
        xo.open("POST",url, true);
        } catch (e) {    
        console.log('problem in open command') ;
    }
    try {
        xo.setRequestHeader("Content-type", "application/x-[URL unfurl="true"]www-form-urlencoded");[/URL]
        xo.send('action=getChatData&timestamp='+timestamp);
    } catch (E) {
        console.log('problem retrieving new chats');
    }
}
function displayUpdatedChats(txt){
    chatTable.innerHTML = txt + chatTable.innerHTML;
}

function sendChat(){
    var cP = document.getElementById('chatPerson');
    var cT = document.getElementById('chatText');
    var chatPerson = cP.value;
    var chatText =  cT.value;
    var data = "action=writeChatData&chatPerson="+chatPerson+"&chatText="+chatText;
    if (!xo) {createObject();}
    xo.onreadystatechange = function () {
            if (xo.readyState == 4) {
                if (xo.status == 200) {
                    if(xo.responseText == '0'){
                        console.log ('problem saving chat data');
                    } else {
                        //cP.value = '';
                        cT.value = '';
                    }
                }
            }
        };
    try {
        xo.open("POST", url, true);
        } catch (e) {    
        console.log('problem in open command') ;
    }
    try {
        xo.setRequestHeader("Content-type", "application/x-[URL unfurl="true"]www-form-urlencoded");[/URL]
        xo.send(data);
    } catch (E) {
        console.log('problem sending data');
    }
    return false;
}
window.onload = function(){
    chatTable = document.getElementById('chatTable');
    timer = setInterval(updateChatRoom, 5000);
};
index.html
Code:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "[URL unfurl="true"]http://www.w3.org/TR/html4/strict.dtd">[/URL]
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
        <script src="chatRoomServer.js"></script>
        <title>Chat Room</title>
    </head>
    <body>
        <div id="chatForm">
            
                Your Name: <input type="text" name="chatPerson" id="chatPerson"/><br/>
                Message: <textarea name="chatText" id="chatText"></textarea><br/>
                <input type="button" name="submit" value="Chat" onclick="sendChat();"/>
        
        </div>
        <div id="chatDiv">
            <table id="chatTable" border="1">
                
            </table>
        </div>
    </body>
</html>

Now I did change the function chats
from
Code:
    function chats(){
        require 'databaseConfig.txt';
        $this->timestamp = time();
        mysql_connect(HOSTNAME, USERNAME, PASSWORD) or die (mysql_error());
        mysql_select_db(DATABASENAME);
        $result = mysql_query("SHOW TABLES LIKE 'chat'");
        if (mysql_num_rows($result) === 0){
            $this->createDatabaseSchema();
        }
        $this->action = isset($_POST['action']) ? $_POST['action'] : 'getChatData';
        $this->switchBoard();
    }
to
Code:
    function chats(){

        $this->timestamp = time();
        $dbserver = mysql_connect('localhost', 'mychat', 'mychat') or die('error');
@mysql_select_db('mychat',$dbserver) or die('error');
        $result = mysql_query("SHOW TABLES LIKE 'chat'");
        if (mysql_num_rows($result) === 0){
            $this->createDatabaseSchema();
        }
        $this->action = isset($_POST['action']) ? $_POST['action'] : 'getChatData';
        $this->switchBoard();
    }
and it is connecting and passing variables to the Database but the chat is not returning the results to the page?.. what have I missed?

I should mention I am using xamp as a local host..

MA WarGod

I believe if someone can think it, it can be programmed
 
Yes but the text isn't where I wish to strip the html its in the username (chatPreson, when entering the room with html tags the full html tag appears at the top of the room, it is that display that I want to strip I would like to strip it that way the user name displays just text, only there for now, as far as the tags being used in the chat part chatPreson is fine..





MA WarGod

I believe if someone can think it, it can be programmed
 
its really in the JavaScript so asking on JavaScript forum

MA WarGod

I believe if someone can think it, it can be programmed
 
Just return the value from php and use that. Since youbare sending it anyway it makes sense to control thee behavior server side.
 
ok so make a $ variable like $SchatPerson ?

so like?
Code:
$_SESSION['chatPerson'] = $SchatPerson;

or does that conflict with
Code:
$_SESSION['chatPerson'] = $chatPerson;

MA WarGod

I believe if someone can think it, it can be programmed
 
wait I think I follow what your saying if I create a row in db named username and the strip the html from chatPreson and Insert it.


MA WarGod

I believe if someone can think it, it can be programmed
 
Code:
[b][COLOR=#0000FF ]function[/color][/b] [b][COLOR=#000000 ]writeChatData[/color][/b][COLOR=#990000 ]()[/color][COLOR=#FF0000 ]{[/color]
[tab][tab][COLOR=#009900 ]$chatPerson[/color] [COLOR=#990000 ]=[/color] [b][COLOR=#0000FF ]empty[/color][/b][COLOR=#990000 ]([/color][COLOR=#009900 ]$_POST[/color][COLOR=#990000 ][[/color][COLOR=#FF0000 ]'chatPerson'[/color][COLOR=#990000 ]])[/color] [COLOR=#990000 ]?[/color] [b][COLOR=#0000FF ]empty[/color][/b][COLOR=#990000 ]([/color][COLOR=#009900 ]$_SESSION[/color][COLOR=#990000 ][[/color][COLOR=#FF0000 ]'chatPerson'[/color][COLOR=#990000 ]])[/color] [COLOR=#990000 ]?[/color] NULL [COLOR=#990000 ]:[/color] [COLOR=#990000 ]([/color][COLOR=#009900 ]$_SESSION[/color][COLOR=#990000 ][[/color][COLOR=#FF0000 ]'chatPerson'[/color][COLOR=#990000 ]])[/color] [COLOR=#990000 ]:[/color] [b][COLOR=#000000 ]trim[/color][/b][COLOR=#990000 ]([/color][b][COLOR=#000000 ]strip_tags[/color][/b][COLOR=#990000 ]([/color][COLOR=#009900 ]$_POST[/color][COLOR=#990000 ][[/color][COLOR=#FF0000 ]'chatPerson'[/color][COLOR=#990000 ]]));[/color]
[tab][tab][COLOR=#009900 ]$chatText[/color] [COLOR=#990000 ]=[/color] [b][COLOR=#0000FF ]empty[/color][/b][COLOR=#990000 ]([/color][COLOR=#009900 ]$_POST[/color][COLOR=#990000 ][[/color][COLOR=#FF0000 ]'chatText'[/color][COLOR=#990000 ]])[/color] [COLOR=#990000 ]?[/color] NULL [COLOR=#990000 ]:[/color] [b][COLOR=#000000 ]trim[/color][/b][COLOR=#990000 ]([/color][COLOR=#009900 ]$_POST[/color][COLOR=#990000 ][[/color][COLOR=#FF0000 ]'chatText'[/color][COLOR=#990000 ]]);[/color]
[tab][tab][COLOR=#009900 ]$_SESSION[/color][COLOR=#990000 ][[/color][COLOR=#FF0000 ]'chatPerson'[/color][COLOR=#990000 ]][/color] [COLOR=#990000 ]=[/color] [COLOR=#009900 ]$chatPerson[/color][COLOR=#990000 ];[/color]
[tab][tab][b][COLOR=#0000FF ]if[/color][/b] [COLOR=#990000 ]([/color][b][COLOR=#0000FF ]empty[/color][/b][COLOR=#990000 ]([/color][COLOR=#009900 ]$chatText[/color][COLOR=#990000 ])[/color] [COLOR=#990000 ]||[/color] [b][COLOR=#0000FF ]empty[/color][/b][COLOR=#990000 ]([/color][COLOR=#009900 ]$chatPerson[/color][COLOR=#990000 ])):[/color]
[tab][tab][tab][b][COLOR=#0000FF ]return[/color][/b] false[COLOR=#990000 ];[/color]
[tab][tab][b][COLOR=#0000FF ]else[/color][/b][COLOR=#990000 ]:[/color]
[tab][tab][tab][COLOR=#009900 ]$query[/color] [COLOR=#990000 ]=[/color] [COLOR=#FF0000 ]"Insert into {$this->table} (chatTimestamp, chatPerson, chatText) values ('%s','%s','%s')"[/color][COLOR=#990000 ];[/color]
[tab][tab][tab][COLOR=#009900 ]$result[/color] [COLOR=#990000 ]=[/color] [b][COLOR=#000000 ]mysql_query[/color][/b][COLOR=#990000 ]([/color][b][COLOR=#000000 ]vsprintf[/color][/b][COLOR=#990000 ]([/color][COLOR=#009900 ]$query[/color][COLOR=#990000 ],[/color] [b][COLOR=#000000 ]array_map[/color][/b][COLOR=#990000 ]([/color][COLOR=#FF0000 ]'mysql_real_escape_string'[/color][COLOR=#990000 ],[/color][b][COLOR=#0000FF ]array[/color][/b][COLOR=#990000 ]([/color][b][COLOR=#000000 ]time[/color][/b][COLOR=#990000 ](),[/color] [COLOR=#009900 ]$chatPerson[/color][COLOR=#990000 ],[/color] [COLOR=#009900 ]$chatText[/color][COLOR=#990000 ]))));[/color]
[tab][tab][tab][b][COLOR=#0000FF ]return[/color][/b] [b][COLOR=#0000FF ]array[/color][/b][COLOR=#990000 ]([/color][COLOR=#FF0000 ]'chatPerson'[/color][COLOR=#990000 ]=>[/color][COLOR=#009900 ]$_SESSION[/color][COLOR=#990000 ][[/color][COLOR=#FF0000 ]'chatPerson'[/color][COLOR=#990000 ]]);[/color]
[tab][tab][b][COLOR=#0000FF ]endif[/color][/b][COLOR=#990000 ];[/color]
[tab][COLOR=#FF0000 ]}[/color]

Code:
$[COLOR=#990000 ]([/color][COLOR=#FF0000 ]'#formChatForm'[/color][COLOR=#990000 ]).[/color][b][COLOR=#000000 ]bind[/color][/b][COLOR=#990000 ]([/color][COLOR=#FF0000 ]'submit'[/color][COLOR=#990000 ],[/color] [b][COLOR=#0000FF ]function[/color][/b][COLOR=#990000 ]([/color]e[COLOR=#990000 ])[/color][COLOR=#FF0000 ]{[/color]
[tab]e[COLOR=#990000 ].[/color][b][COLOR=#000000 ]preventDefault[/color][/b][COLOR=#990000 ]();[/color]
[tab]$[COLOR=#990000 ].[/color][b][COLOR=#000000 ]post[/color][/b][COLOR=#990000 ]([/color]url[COLOR=#990000 ],[/color]$[COLOR=#990000 ]([/color][b][COLOR=#0000FF ]this[/color][/b][COLOR=#990000 ]).[/color][b][COLOR=#000000 ]serialize[/color][/b][COLOR=#990000 ]()[/color] [COLOR=#990000 ]+[/color] [COLOR=#FF0000 ]'&action=writeChatData'[/color][COLOR=#990000 ],[/color] [b][COLOR=#0000FF ]function[/color][/b][COLOR=#990000 ]([/color]d[COLOR=#990000 ])[/color][COLOR=#FF0000 ]{[/color]
[tab][tab][b][COLOR=#0000FF ]if[/color][/b][COLOR=#990000 ]([/color]first[COLOR=#990000 ])[/color][COLOR=#FF0000 ]{[/color]
[tab][tab]   $[COLOR=#990000 ]([/color][COLOR=#FF0000 ]'input[name="chatPerson"]'[/color][COLOR=#990000 ]).[/color][b][COLOR=#000000 ]replaceWith[/color][/b][COLOR=#990000 ]([/color]$[COLOR=#990000 ]([/color][COLOR=#FF0000 ]'<span>'[/color][COLOR=#990000 ]+[/color] d[COLOR=#990000 ].[/color]chatPerson [COLOR=#990000 ]+[/color] [COLOR=#FF0000 ]'</span>'[/color][COLOR=#990000 ]));[/color]
[tab][tab]   first [COLOR=#990000 ]=[/color] [b][COLOR=#0000FF ]false[/color][/b][COLOR=#990000 ];[/color]
[tab][tab][COLOR=#FF0000 ]}[/color]   
[tab][tab][b][COLOR=#000000 ]update[/color][/b][COLOR=#990000 ]();[/color]
[tab][COLOR=#FF0000 ]}[/color][COLOR=#990000 ],[/color][COLOR=#FF0000 ]'json'[/color][COLOR=#990000 ]);[/color]
[tab][b][COLOR=#0000FF ]return[/color][/b] [b][COLOR=#0000FF ]false[/color][/b][COLOR=#990000 ];[/color]
[COLOR=#FF0000 ]}[/color][COLOR=#990000 ]);[/color]
 
Code:
    function getChatData(){
        $return ='';
        $timestamp = isset($_POST['timestamp']) && !is_null($_POST['timestamp']) && $_POST['timestamp'] != '' ? intval($_POST['timestamp']) : 0;
        $query = vsprintf("Select chatID, chatPerson, UserName, chatTimestamp, chatText from {$this->table} where chatTimestamp > '%s' order by chatTimestamp DESC limit 50 ", array(mysql_real_escape_string($timestamp)));
        $result = mysql_query($query) or die(mysql_error());
        while($chat = mysql_fetch_assoc($result)):
            $date = date('Y-m-d H:i:s', $chat['chatTimestamp']);
            $chatText = nl2br($chat['chatText']);
            $UserName = nl2br($chat['UserName']);
            $return .= <<<HTML
    <table border="0" cellpadding="0" cellspacing="0" width="100%" id="AutoNumber1">
    <td id="{$chat['chatID']}">$date&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;{$chat['chatPerson']}<br/>{$chatText}</td>
</table>
HTML;
	

        endwhile;
       return array('timestamp'=>$this->timestamp,'chatText'=>$return);
       
    }

    function writeChatData(){
        $SchatPerson = isset($_POST['chatPerson'])?strip_tags($_POST['chatPerson']):'';
        $chatPerson = empty($_POST['chatPerson']) ? empty($_SESSION['chatPerson']) ? NULL : ($_SESSION['chatPerson']) : trim($_POST['chatPerson']);
        $chatText = empty($_POST['chatText']) ? NULL : trim($_POST['chatText']);
        $_SESSION['chatPerson'] = $chatPerson;

        if (empty($chatText) || empty($chatPerson)):
            return false;
        else:
            $query = "Insert into {$this->table} (chatTimestamp, chatPerson, UserName, chatText) values ('%s','%s','%s','%s')";
            $result = mysql_query(vsprintf($query, array_map('mysql_real_escape_string',array(time(), $chatPerson,  $SchatPerson, $chatText))));
            return $result;
        endif;
    }
  
    function createDatabaseSchema(){
        $query = "    CREATE TABLE  {$this->table} (
                             chatID INT( 11 ) NOT NULL PRIMARY KEY AUTO_INCREMENT ,
                             chatTimestamp INT( 11 ) NOT NULL ,
                             chatPerson LONGTEXT NOT NULL ,
                             UserName varchar( 32 ) NOT NULL ,
                             chatText LONGTEXT NOT NULL
                            )
                  ";
        mysql_query($query) or die(mysql_error());
    }

ok user name is in the db and stripped, I did what is above and it strips in the chat output as well.

I have made $UserName = nl2br($chat['UserName']);, but cann't for the life me make it work in javascript..

MA WarGod

I believe if someone can think it, it can be programmed
 
OK GOT THAT PART!!!

I ended up abit of both of ours and instead of returning chatPerson I reurned UserName, this way chatPreson was stripped as you had it but UserName on lowwer half(chat output) is not



MA WarGod

I believe if someone can think it, it can be programmed
 
ok I am stuck

I would like to be able to toggle <div>'s in the script
here what the user hits now coming to the room
Code:
        <div id="chatForm">
                <form id="formChatForm" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
                Your Name: <input type="text" name="chatPerson" id="chatPerson"/><br/>
                Message: <textarea name="chatText" id="chatText"></textarea><br/>
                <input type="submit" id="xsubmit" name="xsubmit" value="Chat"/>
                </form>
        </div>


I would like a new user to hit this div first then enter the room using the first div

Code:
        <div id="EnterchatForm">
                

                <form id="formChatForm" name="formChatForm" action="<?php echo $_SERVER['PHP_SELF'];?>" method="post">
                Your Name: <input type="text" name="chatPerson" id="chatPerson"/><br/>
			    <input type="text" name="chatText" id="chatText"  value="Enters Chat"/><br/>
                <input type="submit" id="xsubmit" name="xsubmit" value="Chat"/>
                </form>
        </div>

I did find
Code:
// this tells jquery to run the function below once the DOM is ready
$(document).ready(function() {
 
// choose text for the show/hide link - can contain HTML (e.g. an image)
var showText='Show';
var hideText='Hide';
 
// initialise the visibility check
var is_visible = false;
 
// append show/hide links to the element directly preceding the element with a class of "toggle"
$('.toggle').prev().append(' (<a href="#" class="toggleLink">'+showText+'</a>)');
 
// hide all of the elements with a class of 'toggle'
$('.toggle').hide();
 
// capture clicks on the toggle links
$('a.toggleLink').click(function() {
 
// switch visibility
is_visible = !is_visible;
 
// change the link depending on whether the element is shown or hidden
$(this).html( (!is_visible) ? showText : hideText);
 
// toggle the display - uncomment the next line for a basic "accordion" style
//$('.toggle').hide();$('a.toggleLink').html(showText);
$(this).parent().next('.toggle').toggle('slow');
 
// return false so any link destination is not followed
return false;
 
});
});

but not sure this will help me as I seemly can't make it work..

can some put me in the right direction here?

MA WarGod

I believe if someone can think it, it can be programmed
 
Code:
$('document').ready(function(){
   $('#chatForm').hide();
   $('#EnterChatForm').show();
   $('#EnterChatForm #formChatForm').bind('submit', function(e){
     e.preventDefault();
     $.post($(this).attr('action'), $(this).serialize(),function(d){
        //do something with the response
        $('#EnterChatForm').hide();
        $('#chatForm').show();
        //you may need to bind the submit event in chatForm too
     },'json');

   });

});

note that the above works around the error in your html (that you have two elements in the same html that have the same id). it would be better for you to change the duplicate IDs. or even reuse the form and simply dynamically change the contents of the form (in fact that would probably be the most elegant solution).
 
in thinking what you said about a elegant solution.

I came up with this..

Code:
        <script type="text/javascript">
            $('document').ready(function(){
            $('#chatDiv').hide();
            $('#EnterChatDiv').show();
                var url = '<?php echo $_SERVER['PHP_SELF'];?>';
                var timestamp = 0;
                var interval = 5000;
                var first = true;
                $('#formChatForm').bind('submit', function(e){
    e.preventDefault();
    $.post(url,$(this).serialize() + '&action=writeChatData', function(d){
        if(first){
           $('input[name="chatPerson"]').replaceWith($('<span>'+ d.chatPerson + '</span>'));
           first = false;
            $('#EnterChatDiv').hide();
            $('#chatDiv').show();
        }   
        update();
    },'json');
    return false;

});
                var update = function(){
                    $.post(url, 'action=getChatData&timestamp='+timestamp, function(d){
                            timestamp = d.timestamp;
                            $('#chatTable').prepend(d.chatText);
                    }, 'json');
                }
                var timer = setInterval(update, interval);
                update();

            });
        </script>
Code:
        <div id="EnterChatDiv">
                

               <p align="center"><blink><font size="5" color="#FF0000">Hello and Welcome to 
                                  this beta test chat room,</font></blink></p>
                <p align="center"><blink><font size="5" color="#FF0000">This is a non Role play 
                                  room for now..</font></blink></p>

        </div>
This way I avoided the long way around as I played with it for a few hours and the saw this way of doing it.. as you said the chat interface and enter interface are the same why not leave them as such, Thank you for your help here and taking the time to teach me..


MA WarGod

I believe if someone can think it, it can be programmed
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top