Chat: Web based, PHP 101, JavaScript 101 (AJAX), Jabber (IM)

Topics:
JavaScript 101
AJAX 101
PHP 101
AJAX Chat

AJAX 101

AJAX (Aysnchronous JavaScript and XML) is a technique for dynamically altering a page after communicating with the server and without leaving the page.

Essentially it is made possible by the XMLHttpRequest object

AJAX is a bit difficult to get working in a cross platform manner but their are quite a few libraries out there that have done the hard work.

We will use this one: ajax.js

Here is a quick example: A text file on the server named ajax_example.txt:
		Something...
		
The HTML (named ajax_example.html):
<html>
	<head>
		<title>AJAX Example</title>
		<!-- Load up the AJAX External JavaScript file -->
		<script language="JavaScript" src="ajax.js" />

		<!-- Local Javascript Functions and so on -->
		<script language="JavaScript">

			// A variable to hold the interval id
			var interval = null;	
	
			// A function to call our AJAX PHP script
			function call_ajax()
			{
				makeHttpRequest('ajax_example.txt',ajax_return);
			}

			// A function that gets called when ajax returns
			function ajax_return(response)
			{
				document.getElementById("messages").innerHTML = response;
			}
	
			// Setup AJAX function, creates a timeout so that we run something periodically
			function setup_ajax()
			{
				// Set interval of 5000 milliseconds
				// Keeps going...
				interval = setInterval("call_ajax()",5000);

				// Only happens once..
				//interval = setTimeout("call_ajax()",5000);
			}			
		
			// Register setup_ajax with the onload event of the window (when it is done loading)..	
			window.onload = setup_ajax;

		</script>
	</head>
	<body>
		<b>Looky here!</b>
		<div id="messages" style="overflow: auto; width: 500px; height: 400px;">
			Something should pop up here..
		</div>
	</body>
</html>
		
Try It

The above example is very simplistic but a illustrates many points. First of all, the browser loads the HTML and executes the JavaScript contained within ajax_example.html. At the bottom of the JavaScript there is an event "window.onload" which is assigned to run a function called "setup_ajax". This ensures that the "setup_ajax" function will run after the HTML page is rendered and the JavaScript functions are all defined.

The "setup_ajax" function creates an interval (something that happens over and over again) that calls "call_ajax" every 5 seconds.

The "call_ajax" function is where we call "makeHttpRequest" which is a function defined in "ajax.js". This function takes in the URL of the page to call, in this case "ajax_example.txt" and what function to send the source of this page to ("ajax_return").

Essentially, "makeHttpRequest" is functioning as if someone clicked on a link but instead of going to a different page in the browser, the source code of that page get's sent to a JavaScript function. This enables us to modify a page on the fly, perhaps even "live"..

The "ajax_return" function takes in the source of the page that was called and in this case just uses the getElementById and innerHTML methods and properties to modify the current page.

Taking this a step further, we could modify the text file that is being called repeatedly by the AJAX at any time and the change would be reflected on the user's browser.

Consequently we could make a platform which enabled many people at once to experience changes to a file on the server. This could be the basis of a chat room or any other live platform that we choose.

We could also use a bit of some server side programming through PHP to do even more...

Firebug

Firebug is an add-on to Firefox that offers a whole slew of debugging features for working with JavaScript as well as AJAX. Get it! Use it!

AJAX Chat

AJAX Chat is a AJAXification of this chat script: jenChat (although the resemblence is probably very small at this point).

You can download the source (JavaScript and PHP): ajaxchat.zip

Within the ZIP file you will find the following:

ajax.js: The same JavaScript AJAX source described above.
chatmessages.txt: A text file that holds the chat messages. You probably want to clear this file.
index.php: The main chat interface. We'll go through it below.
login.php: Uses PHP session variables
post.php: Takes a normal HTTP POST from a form, opens the chatmessages.txt file and writes out what was submitted.
thread.php: Reads from the chatmessages.txt file and returns what it contains.

IMPORTANT: For login to work correctly, each of the PHP pages that use the "session_start()" command at the top of the page should, just before that, issue the "session_name()" command with a unique string in the parenthesis. This makes it so our server side sessions don't interfere with each-other. This code is currently missing in the zip file so you should go through and add it to all of the PHP pages. Each of your PHP pages should use the same string in the session_name command.

More about index.php:

The following PHP is at the very top of the document:
<?
  session_name('MAKE ME UNIQUE');
  session_start();
  if(!isset($_SESSION['UserID'])) 
  {
    header("Location: login.php");
    //echo "No Session";
    exit;
  }
?>
This section of the code starts the session in PHP and tests to see if the UserID value is set. If it isn't, it redirects the user back to the login.php page to choose a username (and set a session with that handle).

The next important part is the JavaScript:
	
		<script type="text/javascript">
			
			// A variable to hold the interval/timeout id
			var interval = null;	
		
			// A function to call our AJAX PHP script
			function call_ajax()
			{
				makeHttpRequest('thread.php' ,ajax_return);
			}

			// A function that gets called when ajax returns
			function ajax_return(response)
			{
				var chatDiv = document.getElementById("chatmessages");
				
				chatDiv.innerHTML = response;
				chatDiv.scrollTop = chatDiv.scrollHeight;
				interval = setTimeout("call_ajax()",1000);
			}
	
			// Setup AJAX function, creates a timeout so that we run something periodically
			function setup_ajax()
			{
				// Set interval of 5000 milliseconds
				// Keeps going...
				interval = setTimeout("call_ajax()",1000);
			}			
		
			// Register setup_ajax with the onload event of the window (when it is done loading)..	
			window.onload = setup_ajax;

			// Form Sending
			function submit_form()
			{
				// Manually getting the form values and sending them off
				var message = document.forms['theform'].message.value;
				message = encodeURI(message);
				makeHttpRequest('post.php?message=' + message,form_return);	
				document.forms['theform'].message.value = "";
			}
			
			function form_return(response)
			{
				alert(response);
			}
		</script>
Most of the JavaScript is the same as the AJAX example above. The main differences are in the "ajax_return" function which gets what is contained in the "chatmessages.txt" file after the "call_ajax" method is run. It sets the contents of that file to be what is inside the "chatmessages" div using document.getElementById and innerHTML. It also sets the timeout to run "call_ajax" again after 1 second.

The other main point of departure is the "submit_form" function. It is called when the "submit" button is pushed (via the "onclick" event). This function get's what the user typed into the "message" input field, encodes it and then through AJAX sends it to "post.php".

This JavaScript, HTML and PHP is very simplistic. There are a variety of ways that it could be improved or made more useful (such as using MySQL instead of a text file). The simplicity also makes it pretty flexible. For instance, you can easily have it send images/audio/video files to users by using the tags that represent those media.