Jump to content

RandomChatroom


TehBlizzy

Recommended Posts

I've been working quite a bit on the site and the registering script and login script and everything else works, but now the message posting script isn't working. It worked a few days ago but now it isn't... and I don't know why!If it helps, you can log into the site at RandomChatroomUsername: testPassword: test

<?phpsession_start();if(!isset($_SESSION['myusername'])){header("location:http://randomchatrooms.zxq.net/index.php");}echo("<html>	<head>		<meta http-equiv='content-type' content='text/html;charset=iso-8859-1'>		<title>Random Chatroom - Red Room</title><link rel='stylesheet' href='css/red.css' type='text/css'>	</head><script style='javascript'>function ajaxFunction(){  var xmlHttp;  try  {	// Firefox, Opera 8.0+, Safari	xmlHttp=new XMLHttpRequest();  }  catch (e)  {	// Internet Explorer	try	{	  xmlHttp=new ActiveXObject('Msxml2.XMLHTTP');	}	catch (e)	{	  try	  {		xmlHttp=new ActiveXObject('Microsoft.XMLHTTP');	  }	  catch (e)	  {		alert('Your browser does not support AJAX!');		return false;	  }	}  }  data = '';  data += '&UserMsg=' + escape(document.getElementById('UserMsg').value);  data += '&Username=' + escape(document.getElementById('Username').value);  xmlHttp.open('POST','post_msg.php',true);  xmlHttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');  xmlHttp.setRequestHeader('Content-length', data.length);  xmlHttp.send(data)  document.Msg.UserMsg.value=''}</script>	<body bgcolor='000000'>		<center>			<table width='800' border='1' height='500' bordercolor='FF0000'>				<tr height='50'>					<td colspan='2'>						<center>							<h3>Random Chatroom - Red Room</h3>						</center>					</td>				</tr>				<tr height='400'>					<td colspan='2'>						<div align='center'>							<iframe id='the_text' name='the_text' src='chat/red.htm' height='350' width='650' border='0' style='border-color: 000000;border-style: solid;'></iframe></div>					</td>				</tr>				<tr>					<td><div align='center' valign='middle'><br>						<form name='Msg' method='post' onsubmit='ajaxFunction(); return false;' action=''>											Message: <input id='UserMsg' type='text' name='UserMsg' size='70' maxlength='60' id='msg_id'><br><input type='text' name='Username' value='$_SESSION[myusername]' id='Username'> <input type='submit' value='Send!'>							</form></div>					</td>				</tr>				</table>	</body></html>");?>

That is my chatroom page, and this is the message posting script:

<?php$msg = $_POST["UserMsg"];$username = $_POST["Username"];$newmsg = str_replace("<","<","$msg");$file = fopen("chat/red.htm","r+");fwrite($file,"{$username} says: {$newmsg} <br>") or die("Couldnt write to file");fclose($file);?>

Link to comment
Share on other sites

You've wasted too much energy on styles and tables and stuff when you should be concentrating just on communicating between the client and the server, back and forth.What you need most is a readystate function attached to your http object to retrieve what your script sends back. Why aren't you using one of a thousand sets of ready-made functions just for this purpose posted all over the web, including here?When you have that, try echoing $_POST["UserMsg"] and $_POST["Username"] as soon as you get them.An ajax test is really simple. Send something to the server, send it back, display it. That's your engine. Build everything around the engine, not the other way around.

Link to comment
Share on other sites

I don't have any "readystate" functions because 75% of the PHP I googled and or recieved examples of from my other two posts about different problems about different things on this forum.The registering script works, the user login script works, but now the message script doesn't work. I basically used what help I've obtained in my other post about the message script and just changed a few variables.Javascript - Random Chatroom..Plus, there is nothing too detailed about my layouts, all the CSS is in a separate file. Nothing but tables, tds, trs, and divs :|

Link to comment
Share on other sites

This is one thing that's getting in the way: parent.the_text.window.location.reload; You have absolutely no guarantee that the file will be fetched after you're script has written to it. So the behavior will be most erratic.Why would you want to reload the iFrame if you're using AJAX? The whole point behind AJAX is to establish p2p communication without having to reload pages.I guess you're trying to simulate this with your iFrame? But that misses the point entirely. Make that iFrame a div. It'll be easier that way, anyhow, since red.htm won't have to be a completely formed html page. Just a lot of text, which you could name red.txt, if you choose.If you have a readystate function in your javascript, then you can receive data from your server without reloading ANY page or frame. This data can be the complete text of your chat, if you want, or just the most recent messages. When you get it ( in your xmlHttp.responseText variable) add it to your or append it to the innerHTML of your display div.SUMMARYNow that I've looked at this a bit more closely, I think the problem is you're combining 1990s iFrame technology with 21st C AJAX technology, and the bits that don't match are getting in your way. I suggest you eliminate the iFrame entirely. Save your communication in a plain text file. (It can include HTML tags.) Once the client file is loaded in the browser, no more reloads. Your browser should communicate with the server 100% through AJAX. New text messages go to the server script. The script writes them to the end of the data file, and then returns the contents of the file (or just the most recent contents) to the browser through the xmlHttp.responseText variable. The browser then puts that info where it wants.Now, try using these 3 javascript functions to do what you need. The php is not much different than responding to any post request, except that you only send the data you need to, you don't send a whole page.

<script type="text/javascript">    var hObj;    function hPostData(myData) { // data looks like a normal post, with & and + chars        hObj = null;        var myURL = "ajax.cgi";        if (hObj = getHObject()){            hObj.onreadystatechange = hStateChanged;            hObj.open ('POST', myURL, true);            hObj.send (myData);        }else {alert ("Cannot get an HTTP object");}    }    function hStateChanged() {         if (hObj.readyState == 4) {            if (hObj.status == 200) {                handle_this_data_anyway_you_want(hObj.responseText);            }else{                alert ('Sorry: ' + hObj.status);            }        }    }    function getHObject() {        var hObj = null;        try {hObj = new XMLHttpRequest();}        catch (e) {            try {hObj = new ActiveXObject('Msxml2.XMLHTTP');}            catch (e) {hObj = new ActiveXObject('Microsoft.XMLHTTP');}        }        return hObj;    }</script>

Link to comment
Share on other sites

I needed to work on some chatroom foundations, so I hacked this out for both of us. It'll get you started. Please tell me you can integrate this with your file/db stuff and sessions or other manner of sending the message out to all users.ajax.php

<?php	if (!isset($_POST['data'])		|| empty($_POST['data'])			|| !isset($_POST['name'])				|| empty($_POST['name']) ) {?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>	<head>		<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">		<title>AJAX sample</title>		<style type="text/css">			* {				font-family: Verdana;				margin: 0;				font-size: 1em;				color: #bb0000;				margin: 0 auto;			}			html, body {				text-align: center;				background-color: #000000;				margin: 0 auto;			}			h1 {				padding: 20px;			}			div {				border: solid 1px #bb0000;				background-color: #000000;			}			#response {				height: 300px;				width: 800px;				background-color: #000000;				text-align: left;				padding: 10px;			}			#panel {height: 100px;				width: 800px;				background-color: #000000;				margin-top: 20px;				padding: 10px;			}			label{				border: solid 1px #000000;				color: #bb0000;				font-size: .8em;				font-weight: bold;				height: 20px;				background-color: #000000;				margin-top: 20px;			}			input[type="text"] {				border: solid 1px #bb0000;				font-size: .8em;				height: 20px;				background-color: #000000;				margin-top: 20px;				padding-left: 5px;				padding-right: 5px;			}			#name {				width: 80px;				margin-left: 5px;			}			#msg {				width: 600px;				margin-left: 10px;			}			#sub {				border: solid 1px #bb0000;				margin-top: 20px;				margin-right: 30px;				background-color: #bb0000;				color: #000000;				font-weight: bold;				float: right;			}			</style>		<script type="text/javascript">				function gg (i) {				return document.getElementById(i);			}				function init () {				http_url = "ajax.php";				http_obj = null;				synch_mode = true;			}						function h_gather_and_post () {				var data = "name=";				data += gg("name").value;				data += "&";				data += "data=";				data += gg("msg").value;				hPostData (data, http_url, synch_mode);			}			function hPostData(myData, my_url, synch_mode) {				http_obj = null;				if ( http_obj = get_http_object()) {					 http_obj.onreadystatechange = h_state_changed;					 http_obj.open ('POST', my_url, synch_mode);					 http_obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");					 http_obj.send (myData);				} else {					alert ("Cannot get an HTTP object");				}			}			function h_state_changed() {				if ( http_obj.readyState == 4) {					if ( http_obj.status == 200) {						h_text_response (http_obj.responseText);					} else {						alert ('Sorry: ' +  http_obj.status);					}				}			}			function h_text_response (text) {				gg("response").innerHTML += text;			}			function get_http_object() {				var http_object = null;				try {http_object = new XMLHttpRequest();}				catch (e) {					try {http_object = new ActiveXObject('Msxml2.XMLHTTP');}					catch (e) {http_object = new ActiveXObject('Microsoft.XMLHTTP');}				}				return http_object;			}			window.onload = init;					</script>	</head>	<body>		<h1>AJAX TEST ROOM</h1>		<div id="response"></div>		<form method="post" action="" onsubmit="h_gather_and_post(); return false">			<div id="panel">				<label>NAME</label><input type="text" id="name"><input type="text" id="msg">				<br>				<button type="submit" id="sub">Post message</button>			</div>		</form>	</body></html><?php	} else {		#append the data to your db, etc. You'll need to add a lot of stuff with sessions and things to update yur other users				header("Content-type: text/plain");			$D = $_POST['data'];		$S = $_POST['name'];		echo "$S: $D<br>";	}?>

Link to comment
Share on other sites

I was about to try out your supplied code but Zymic seems to be having loadign issues again. :[i'm guessing the code you just posted would be the whole chatroom page or just parts of it?

Link to comment
Share on other sites

Ok, Zymic is working and I made a page with the code you supplied, but I've already found an error:

<?php	if (!isset($_POST['data'])		|| empty($_POST['data'])			|| !isset($_POST['name'])				|| empty($_POST['name']) ) {?>

Link to comment
Share on other sites

The code I posted is a complete script, but not a complete chatroom. The code you posted doesn't look like an error. Is your interpreter saying it's an error? Did you run the page exactly as I gave it to you before you started messing with it?

Link to comment
Share on other sites

Beats me. That curly brace that "doesn't do anything" is standard PHP syntax. What it means is this. If the condition is met, do the stuff inside the curly braces. The closing curly brace is in the php section AFTER the html. And that's OKAY, regular php, even if you haven't seen it before. The idea is, if the condition is met, then print the html. Otherwise, jump to the php section at the bottom. I am not making this up.To see it work, go here. http://sophox.com/scripts/ajax.php . It's not just pasting the message into the top box; it's sending it to the server, and the server sends it back. Then it gets pasted to the top box. That's what I wanted to show you. And that's the same script you have.Either way, you can use all the javascript functions without much change, and the little php code at the bottom of the script shows you just how easy a postback can be. So if worse comes to worst, you can watch what it does from my server, and then look at the code and try to figure out what's happening.Maybe the copy/paste did something weird with returns or something.

Link to comment
Share on other sites

I went to the link, and it loads, but the messages don't post, or are they supposed to?I think the reason why it isn't "posting" a message is the page is reloading, even though it's not supposed to. I think our school's IE version must ######...

Link to comment
Share on other sites

Yeah, you hit submit or the enter key, and you should get stuff on the big window on top.I might know what the problem is. I didn't think about where you guys are. Our local schools have cruddy computers, too, unless you're in the business classes. I probably did a stupid thing and tried to modernize a little. I took that out and put some more old-fashioned stuff back. It works on Firefox 2.x.x.14 and Safari 3x, both Mac, but earlier versions should work too, since there's nothing weird here. And it works on Windows IE7. It should work on IE6, but I can't test that. If you're on IE 5.5, I may have fixed it. Don't know. That's really old.I've updated the code that I posted above, too, so if you want to try it, you'll have to copy it again. (Actually, you just need to replace the get_http_object() function.

Link to comment
Share on other sites

I'm in a different classroom now, and I just tried the ajax chatroom, and it works. I don't know why the other classroom's computer doesn't work...
Oh good. The thought that TehBlizzy and Zymic thought I was a lunatic was keeping me up at night. :)
Link to comment
Share on other sites

I told Dierdre's Dad that too...

Beats me. That curly brace that "doesn't do anything" is standard PHP syntax. What it means is this. If the condition is met, do the stuff inside the curly braces. The closing curly brace is in the php section AFTER the html. And that's OKAY, regular php, even if you haven't seen it before. The idea is, if the condition is met, then print the html. Otherwise, jump to the php section at the bottom. I am not making this up.
I copied the exact same code he posted but it has that error.
Link to comment
Share on other sites

Here's an idea. Change the .php extension on that file to .txt. Maybe if I see what you're actually processing, I can see what might have gotten changed.I want to know this because I'm curious.If I can't find it, I'll just hack some new files together. Won't take long.BTW, don't try getting sympathy about the bracket on line one from justsomeguy, because he knows exatly what I'm doing. He practically wrote the book on PHP. Or at least, he read one. That is, he sent one through the mail once . . . it wasn't about PHP, though. It might even have been illegal, since he sent it to a Bulgarian.

Link to comment
Share on other sites

... Where are you getting all of that? I copied exactly what you posted and put it up at http://randomchatroom.zxq.net/ajax.php and its coming up with the same sytax error...(Your exact code for ajax.php)

<?php	if (!isset($_POST['data'])		|| empty($_POST['data'])			|| !isset($_POST['name'])				|| empty($_POST['name']) ) {?><!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"><html>	<head>		<meta http-equiv="content-type" content="text/html;charset=iso-8859-1">		<title>AJAX sample</title>		<style type="text/css">			* {				font-family: Verdana;				margin: 0;				font-size: 1em;				color: #bb0000;				margin: 0 auto;			}			html, body {				text-align: center;				background-color: #000000;				margin: 0 auto;			}			h1 {				padding: 20px;			}			div {				border: solid 1px #bb0000;				background-color: #000000;			}			#response {				height: 300px;				width: 800px;				background-color: #000000;				text-align: left;				padding: 10px;			}			#panel {height: 100px;				width: 800px;				background-color: #000000;				margin-top: 20px;				padding: 10px;			}			label{				border: solid 1px #000000;				color: #bb0000;				font-size: .8em;				font-weight: bold;				height: 20px;				background-color: #000000;				margin-top: 20px;			}			input[type="text"] {				border: solid 1px #bb0000;				font-size: .8em;				height: 20px;				background-color: #000000;				margin-top: 20px;				padding-left: 5px;				padding-right: 5px;			}			#name {				width: 80px;				margin-left: 5px;			}			#msg {				width: 600px;				margin-left: 10px;			}			#sub {				border: solid 1px #bb0000;				margin-top: 20px;				margin-right: 30px;				background-color: #bb0000;				color: #000000;				font-weight: bold;				float: right;			}			</style>		<script type="text/javascript">				function gg (i) {				return document.getElementById(i);			}				function init () {				http_url = "ajax.php";				http_obj = null;				synch_mode = true;			}						function h_gather_and_post () {				var data = "name=";				data += gg("name").value;				data += "&";				data += "data=";				data += gg("msg").value;				hPostData (data, http_url, synch_mode);			}			function hPostData(myData, my_url, synch_mode) {				http_obj = null;				if ( http_obj = get_http_object()) {					 http_obj.onreadystatechange = h_state_changed;					 http_obj.open ('POST', my_url, synch_mode);					 http_obj.setRequestHeader("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");					 http_obj.send (myData);				} else {					alert ("Cannot get an HTTP object");				}			}			function h_state_changed() {				if ( http_obj.readyState == 4) {					if ( http_obj.status == 200) {						h_text_response (http_obj.responseText);					} else {						alert ('Sorry: ' +  http_obj.status);					}				}			}			function h_text_response (text) {				gg("response").innerHTML += text;			}			function get_http_object() {				var http_object = null;				try {http_object = new XMLHttpRequest();}				catch (e) {					try {http_object = new ActiveXObject('Msxml2.XMLHTTP');}					catch (e) {http_object = new ActiveXObject('Microsoft.XMLHTTP');}				}				return http_object;			}			window.onload = init;					</script>	</head>	<body>		<h1>AJAX TEST ROOM</h1>		<div id="response"></div>		<form method="post" action="" onsubmit="h_gather_and_post(); return false">			<div id="panel">				<label>NAME</label><input type="text" id="name"><input type="text" id="msg">				<br>				<button type="submit" id="sub">Post message</button>			</div>		</form>	</body></html><?php	} else {		#append the data to your db, etc. You'll need to add a lot of stuff with sessions and things to update yur other users				header("Content-type: text/plain");			$D = $_POST['data'];		$S = $_POST['name'];		echo "$S: $D<br>";	}?>

Link to comment
Share on other sites

cool.gifRelax, dude. All I was wondering is if the copy/paste did any malformations. And clearly the line breaks got freaked all the heck. Not your fault. Just copying from the web does weird stuff. I just want to see if all the freaking did some kind of damage.And if makes you any happier, I've been spending my lunch break actually making you a real chat room. So grab a Sobe and chill, K?
Link to comment
Share on other sites

There you go, nice and simple. Because php lines end with semicolons, weird line breaks don't affect them.This is not true of comments. Stick a line break in the middle of a comment, and the second half of the comment will get read as a line that makes no sense. Everything after it will be garbage too.So all you have to do to play around with this thing is remove these words, which you'll find near the bottom:#append the data to your db, etc. You'll need to add a lot of stuff with sessions and things to update yur other usersThe reason the interpreter flagged the opening brace is that it couldn't find a closing brace, because the closing brace is on the other side of that comment, and everything there got turned into garbage.Like I said, not your fault. But not mine either.

Link to comment
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...