Tutorials

Processing Overview

Tagged:  

John Resig has written a good overview of Processing. Processing is a data visualization language written in Java that has been compared favorably to Flash. I first saw the language a couple of years ago and was very interested in it, but haven't seen much on it until this.

Below is an excerpt from the post.

Processing is a data visualization programming language.

It has three components:

  • The Processing language
  • The Processing drawing API
  • The implementation (in Java - can optionally pass the drawing API through to OpenGL).

The Processing Language and API

  • Strictly typed
  • Has classes, inheritance
  • Includes a bunch of globally-accessible functions (the drawing API - very flat and PHP-like).

Basic Program Structure

Two core methods: setup() and draw()

  • Very OpenGL-like
  • draw() is called continually at a specific framerate (if none is specified then it goes as fast as possible)

Simple example: Drawing a continuous line with the mouse.

void setup() {
  size(200, 200);
  background(102);

}

void draw() {
  stroke(255);
  if(mousePressed) {

    line(mouseX, mouseY, pmouseX, pmouseY);
  }
}

You can read the full post here.

Processing is a very interesting language and I could see it being very useful for applications that need a better way to represent information than is available in browser rendering. If you have never seen Processing, then you should look at some of the examples in John's post.

Google Code University

Tagged:  

If you're interested in learning more about Ajax development, distributed systems, web security, or C++/Java/Python and you haven't checked out Google Code University, you're missing out on a valuable educational resource on these topics and more.

Here's a sample video from the site:
Web 2.0 - AJAX - Creating a Rich User Experience

    Description: Incorporated AJAX is enabling the creation of applications with better functionality, usability, and an overall better user experience. This panel will discuss how desktop-like applications can be delivered via the browser with Ajax, the efficiency of developing such applications, and the importance of the GUI. They will also share their thoughts on highly successful applications and the shortcomings of using Ajax.

Also on the site, you'll find a series of Web Programming lecture slides provided by the University of Washington.



For these and other great resources, visit the Google Code University

Creating Resizeable Buttons in CSS

Tagged:  

Have you ever designed a page for a web application and wanted to make a nice button for the application? You probably opened your photo editor and started working on the button. But, what if your design resizes itself based on the users browser size? You will probably want the button to resize as well. Well, over at CSS Globe they have written a script to do just that using CSS.

Below is an excerpt from the article explaining the concept.

Concept

This concept is probably familiar to you from various navigation tab styling techniques. We have one long background image:

image

This one is 550px wide. I believe that is more than sufficient for buttons :)

So, we apply this image as a background image of a top element (in this case SPAN), place it to top left and add some left padding. Nested element (in this case EM) have the same background image but placed to top right and with right padding. As the content text grows so will the button.

image

Height of the button is fixed in my example but you can use similar technique and some more markup and place the same background image to all 4 corners.

To make sure that the text is vertically centered I use line-height property.

The HTML that is required for applying the CSS to would be the below.

<button><span><em>Button text</em></span></button>

The below is the CSS that is used.

button{
	border:none;
	background:none;
	padding:0;
	margin:0;
	width:auto;
	overflow:visible;					
	text-align:center;	
	white-space:nowrap;	
	height:40px;
	line-height:38px;			
	}
button span, button em{
	display:block;
	height:40px;
	line-height:38px;			
	margin:0;
	color:#954b05;
	}
button span{
	padding-left:20px;
	background:url(bg_button.gif) no-repeat 0 0;
	}	
button em{
	font-style:normal;
	padding-right:20px;
	background:url(bg_button.gif) no-repeat 100% 0;
	}

You can read the full post here.

You can see the demo here and you can download the source code and image here.

This code could be very useful and I will probably use it in my next application. If you have used a technique like this in an application that you've made I'd love to hear about it, you can leave it in the comments.

Beginner CSS Tutorial

Tagged:  

I came across this beginner CSS tutorial I'd like to share with those of you that haven't had much experience with CSS.

Topic's include:
* What Is CSS?
* CSS Selectors
* CSS Units
* CSS Inline
* CSS Internal
* CSS External
* CSS Colors
* CSS Fonts
* CSS Text

Here's an excerpt from the tutorial on the advantages of CSS:

* Quick layout changes: Because all your CSS styles are in one or more .css files which are re-used for all pages it's easy to change the look of your website. For instance to add a 5 pixel wide red border to all your images you can simply write img {border:5px solid red}. This saves a lot of time as opposed to changing every single image tag in all your pages.
* Smaller file size: Separating content from presentation helps keep HTML file sizes down and improves page loading times. Once CSS files have been loaded for the first time they will be cached by the browser and loaded instantly for all following pages that use the same style sheets.
* Consistency: With CSS it's easy to keep a consistent look throughout your website.
* Cascading: Multiple style definitions will cascade into one, i.e. the last written one will overwrite all previous ones. This is very useful if you need to work with an existing style sheet and want to make some changes without altering the original code.
* Accessibility: Having content separated from presentation is a great help to people with viewing disabilities who often benefit from well structured HTML to understand the page.
* Design without tables: Before CSS lots of web designers mis-used tables to position elements on their page which is a bad thing for accessibility and also makes the code unnecessarily big and complicated. With CSS you can position any element exactly where you want without using tables.

Click here to visit the tutorial

jQuery Tutorials for Designers

jQuery is a great library for animation and Ajax calls. As with any JavaScript library there are different objects and name spaces to learn. Well, over at Web Designer Wall they have put together a good tutorial about using jQuery. The tutorial is written from a designers stand point, but even an experienced hard-core web programmer can find this tutorial useful.

Below is an excerpt from the post:

How jQuery works?

First you need to download a copy of jQuery and insert it in your html page (preferably within the <head> tag). Then you need to write functions to tell jQuery what to do. The diagram below explains the detail how jQuery work:

how jquery works

How to get the element?

Writing jQuery function is relatively easy (thanks to the wonderful documentation). The key point you have to learn is how to get the exact element that you want to apply the effects.

  • $("#header") = get the element with id="header"
  • $("h3") = get all <h3> element
  • $("div#content .photo") = get all element with class="photo" nested in the <div id="content">
  • $("ul li") = get all <li> element nested in all <ul>
  • $("ul li:first") = get only the first <li> element of the <ul>

1. Simple slide panel

Let’s start by doing a simple slide panel. You’ve probably seen a lot of this, where you click on a link and a panel slide up/down. (view demo)

sample

When an elment with class="btn-slide" is clicked, it will slideToggle (up/down) the <div id="panel"> element and then toggle a CSS class="active" to the <a class="btn-slide"> element. The .active class will toggle the background position of the arrow image (by CSS).

$(document).ready(function(){

	$(".btn-slide").click(function(){
	  $("#panel").slideToggle("slow");
	  $(this).toggleClass("active");
	});

});

2. Simple disappearing effect

This sample will show you how to make something disappear when an image button is clicked. (view demo)

sample

When the <img class="delete"> is clicked, it will find its parent element <div class="pane"> and animate its opacity=hide with slow speed.

$(document).ready(function(){

	$(".pane .delete").click(function(){
	  $(this).parents(".pane").animate({ opacity: "hide" }, "slow");
	});

});

3 Chain-able transition effects

Now let’s see the power of jQuery’s chainability. With just several lines of code, I can make the box fly around with scaling and fading transition. (view demo)

sample

Line 1: when the <a class="run"> is clicked

Line 2: animate the <div id="box"> opacity=0.1, left property until it reaches 400px, with speed 1200 (milliseconds)
Line 3: then opacity=0.4, top=160px, height=20, width=20, with speed "slow"
Line 4: then opacity=1, left=0, height=100, width=100, with speed "slow"

Line 5: then opacity=1, left=0, height=100, width=100, with speed "slow"
Line 6: then top=0, with speed "fast"
Line 7: then slideUp (default speed = "normal")
Line 8: then slideDown, with speed "slow"

Line 9: return false will prevent the browser jump to the link anchor

$(document).ready(function(){

	$(".run").click(function(){

	  $("#box").animate({opacity: "0.1", left: "+=400"}, 1200)
	  .animate({opacity: "0.4", top: "+=160", height: "20", width: "20"}, "slow")
	  .animate({opacity: "1", left: "0", height: "100", width: "100"}, "slow")
	  .animate({top: "0"}, "fast")
	  .slideUp()
	  .slideDown("slow")
	  return false;

	});

});

4a. Accordion #1

Here is a sample of accordion. (view demo)

sample

The first line will add a CSS class "active" to the first <H3> element within the <div class="accordion"> (the "active" class will shift the background position of the arrow icon). The second line will hide all the <p> element that is not the first within the <div class="accordion">.

When the <h3> element is clicked, it will slideToggle the next <p> and slideUp all its siblings, then toggle the class="active".

$(document).ready(function(){

	$(".accordion h3:first").addClass("active");
	$(".accordion p:not(:first)").hide();

	$(".accordion h3").click(function(){

	  $(this).next("p").slideToggle("slow")
	  .siblings("p:visible").slideUp("slow");
	  $(this).toggleClass("active");
	  $(this).siblings("h3").removeClass("active");

	});

});

4b. Accordion #2

This example is very similar to accordion#1, but it will let you specify which panel to open as default. (view demo)

In the CSS stylesheet, set .accordion p to display:none. Now suppose you want to open the third panel as default. You can write as $(".accordion2 p").eq(2).show(); (eq = equal). Note that the indexing starts at zero.

$(document).ready(function(){

	$(".accordion2 h3").eq(2).addClass("active");
	$(".accordion2 p").eq(2).show();

	$(".accordion2 h3").click(function(){
	  $(this).next("p").slideToggle("slow")
	  .siblings("p:visible").slideUp("slow");
	  $(this).toggleClass("active");
	  $(this).siblings("h3").removeClass("active");
	});

});

You can read the full post here.
You can also view the demo here or download the demo code here.

jQuery is one library that I really recommend using. The library is very well written and is pretty easy to learn fairly quickly. If you haven't used the library before this is a good tutorial to start with.

JavaScript Debugging in Internet Explorer

For those of us who have lamented the sad state of debugging in Microsoft's Internet Explorer (and no, the Microsoft Script Debugger doesn't count), some relief is here. Complementing the IE Developer Toolbar, the Microsoft Visual Studio 2008 Web Developer Express Edition (and previously the 2005 Express Edition) gives you full JavaScript debugging ability from within the VS development environment without needing the paid version. The only drawback vis-a-vis the professional edition is that the page must be launched from with the IDE (rather than from IE itself). A small price to pay for desperately needed functionality.

Here's some quick steps to get you started:

1. Download the Web Developer Express Edition for free (though registration is required to activate it).
2. Create an empty web site, File-->Web Site...-->Empty Web Site.
3. Deposit the files you wish to debug in the web site folder, and open the file you wish to debug. Place desired break points. (Or you can skip this step if you just intend to just navigate to a URL later.)
4. Click the "Start Debugging" button. If you skipped step #3 and wish to navigate to a URL, then you may want to put at least one debugger statement in your JavaScript code so that the debugger will stop at this statement. Breakpoints can then be set within the IDE elsewhere.
5. Controls are in the Debug menu. F10 will step over, F11 will step into, etc.
6. All the expected debugging views are there: Call Stack, Locals (variables), Watch, and so forth.

Not quite as convenient as having Firebug directly in your browser, but a first-class JavaScript debugger (as JavaScript debuggers go...) nonetheless.

Creating a Simple JavaScript Game Board

Over at the Web Cash blog they have posted two tutorials on Game development in JavaScript, Ajax and PHP. The first tutorial explains the concept and describes how to make a game board.

Below is an excerpt from the first tutorial.

Game Development with JS, AJAX, and PHP

How can we use JS and PHP - connected through AJAX - to develop an online game?

Javascript’s main use for us is to create an interface for the game. Through Javascript we can capture user input - i.e. mouse clicks and text. We can also alter the game’s output - changing the HTML of the page, adding images, and moving things around. Javascript will provide a lot of the front end work.

PHP, on the other hand, is a more robust language for dealing with the logic of the game. PHP could be useful for developing an AI and evaluating winning conditions. It also offers a great way to store information for later use through flat files or database integration.

If we’re going to use both Javascript and PHP, we’ll need to use AJAX. This is the glue that holds the whole thing together. It will send input from the main Javascript to the PHP processing scripts. The PHP script will then send info back to the Javascript and it will alter the page’s layout accordingly.

Read the full first tutorial here.

The second tutorial goes into more detail as to how you would start creating a simple game. By the end of the tutorial you have a complete simple tic-tac-toe game (the game needs more logic added to be finished, but the concept is there).

Below is an excerpt from the second tutorial.

Creating Graphics

Tic Tac Toe Circle ImageI created two images in Inkscape to use for this board. Each is a 50×50 png file - with a gray background and a black border. The actual token (the circle or cross) is red and laid on top of the gray background.

Tic Tac Toe Cross ImageI’m no great artist, but these should work for a functional demo. We can worry about making nice circle and cross tokens later. I think getting the game working is more important than making it pretty from the get-go.

Turning Our .js Script into a Class

In making this a functional board, I also converted the script into an actual class. The script may end up being somewhat large and unwieldy - and an object oriented approach may help us keep it tidy and clean. Or it may add a lot of overhead… but I like objects.

In our HTML file, we’ll create the object like this.

<script type="text/javascript">
var tictactoe = new game();
</script>

In the attached .js file, we actually define the game object. Here’s part of the object definition.

function game() {
  //  Array to hold the bgImgs
  this.bgImgs = new Array();
    this.bgImgs[0] = 'tttcircle.png';
    this.bgImgs[1] = 'tttcross.png';

 
  //  Player information			
  this.currentPlayer = 0;
  this.players = new Array();
    this.players[0] = "Player One";
    this.players[1] = "Player Two";

 
   return true;

This class constructor does some of the initialization for us.

First, it creates an array with background images. At the moment we’re only using two images. However, this technique would be useful if you had a more complex map - with 10-15 images you could lay over a div.

Second, we create some player information variables. The ‘currentPlayer’ property is going to track whether the ‘cross’ or ‘circle’ player is currently taking a turn. The ‘players’ array will just hold the names of those players for now.

The Background Image Changing Function

One of the major methods of this class will be changeBackground(). Just like in the previous example, this method will change the background style of a given div tag. This way we can change it from an open square to a circle or cross token.

  this.changeBackground = function (boxId) {
    var box = document.getElementById('box-' + boxId);
    box.style.background = 'transparent url(' + 
      this.bgImgs[this.currentPlayer] + ') top left no-repeat';

 
    box.removeAttribute('onClick');
 
    this.changePlayer();
  }

This should be pretty straightforward. We’re storing the ‘div’ element in the ‘box’ variable. We’re then setting the ‘background’ style as we would in a css style. Remember that we stored the background images in an array (this.bgImgs) and this.currentPlayer corresponds to a key in the this.bgImgs array (either 0 or 1).

The ‘box.removeAttribute()’ method is removing ‘onClick’ from that div. We can’t use a square a second time, so we might as well eliminate the onClick handler altogether.

Finally, this.changePlayer() is calling a new method. This is going to help us switch from Player One’s turn to Player Two’s turn.

One Turn to Another - this.changePlayer()

The last method we need to declare for this class at the moment is changePlayer.

This will toggle the active player - which in turn affects whether a circle or cross is placed on the board. For some added effect, we’ll also create a new html element to display a message that says who’s turn it is.

  this.changePlayer = function () {
    //  Switch the active player

    if (this.currentPlayer == 0) {
      this.currentPlayer = 1;
    } else {

      this.currentPlayer = 0;
    }
 
    //  Get a reference to our 'message' element and create the message
    var box = document.getElementById('message');
    var msg = "It is " + this.players[this.currentPlayer] + "'s turn.";
    var txt = document.createTextNode(msg);

 
    //  Erase any existing text
    while (box.hasChildNodes()) {
      box.removeChild(box.lastChild);
    }

 
    //  Add the text node (our message) to our element
    box.appendChild(txt);
  }

Again, this is pretty straightforward. The DOM functions are amazingly simple - once you see how they work.

‘box’ is a reference to our element (id = message). The msg variable is a temp variable I created to hold the string. The ‘createTextNode’ method creates a new block of text (with our msg) that we can then insert into an HTML element.

The while() loop is simply there to erase any old text. As long as our ‘box’ element has any child nodes inside of it (text or other HTML tags), the loop will execute and delete one of those child nodes each time. This way we have a clean slate on which to write down who’s turn it is.

Read the full second tutorial here.

Although the tutorial only shows a simplistic tic-tac-toe game you could use the concepts as a starting point to build your own web games. As always if you have made any cool games we would love to hear about them either in the comments or you can write a blog post about it using your free Ajaxonomy account.

Create Resizing Thumbnails

Tagged:  

Have you ever been designing a web page or web application that displayed quite a few thumbnails? Perhaps at times it would be nice to have larger thumbnails, but the page design didn't allow for it. Well over at cssglobe.com they have an interesting post about resizing thumbnails so you can enlarge the thumbnails when the mouse is over the thumbnail.

Below is an excerpt from the post.

The Concept

The idea behind this is, to place an image into a certain container. Since we're talking about thumbnails that container would be an <a> tag. We set the size (width and height) of the container to desired values and we set the position property of the container to relative. Image inside has an absolute position. We use negative top and left values to offset the image. Container has overflow set to hidden so only a part of the image that is placed inside the container's actual area will be visible. The rest of it will be hidden. On a:hover we set the container's overflow to visible, and reveal entire image.

overflow thumbnails

The Code

This trick can be used for thumbnail lists or single thumbnails, as shown on the demo page. For markup we use standard tags

<a href="#"><img src="image.jpg"  alt="my image" /></a>

Definition of the default state for thumbnails would be something like this:


	ul#thumbs a{
		display:block;
		float:left;
		width:100px;
		height:100px;
		line-height:100px;
		overflow:hidden;
		position:relative;
		z-index:1;		
	}
	ul#thumbs a img{
		float:left;
		position:absolute;
		top:-20px;
		left:-50px;	
	}

<a> tag has defined width and height to whatever fits into our site's design. Also, overflow is set to hidden. We then play with negative top and left values to "crop" the image to a perfect fit. If you want to take this further, you can define cropping area for every single image you have in thumb list and target the area you would like to show.

 	
	ul#thumbs a img{
		float:left;
		position:absolute;
		top:-20px;
		left:-50px;	
	}
	ul#thumbs li#image1 a img{
		top:-28px;
		left:-55px;	
	}	
	ul#thumbs li#image2 a img{
		top:-18px;
		left:-48px;	
	}	
	ul#thumbs li#image3 a img{
		top:-21px;
		left:-30px;	
	}	
	.
	.
	.		

Now, when user mouse-overs it we set the overflow to visible:

		ul#thumbs a:hover{
			overflow:visible;
			z-index:1000;
			border:none;		
		}

Note the z-index for both default and hovered container. This is very important because we want to place the hovered above it's siblings. Otherwise it would be placed below and the trick wouldn't be complete.

You can read the full post here.

You can view the demo here and you can download the code here.

If you use this on any sites or applications, I'd love to hear about them. You can post them in the comments or you can write a post on this blog once you sign-up for a free account.

script.aculo.us Tutorial

The folks over at Tutorials Point have posted a good tutorial for learning script.aculo.us on their site. The tutorial does well to cover the framework, includes lots of codes examples, and even has a W3C Schools style "try-it-yourself" editor to let you play with the demos. Get started with the tutorial by accessing the sections below:

  1. Short Overview: Gives a brief overview of script.aculo.us.
  2. Major Modules : List out all the modules supported by script.aculo.us.
  3. Visual Effects : Gives complete understanding on creation of visual effects using script.aculo.us.
  4. Drag & Drop: Explains Drag and Drop functionality in detail.
  5. Sorting Elements: Learn how to sort various elements using drag and drop functionality.
  6. Create Sliders: Yes, you can provide a multi purpose slider at your web site
  7. Auto Completion: Explains how to implement Auto Completion
  8. In Place Editing: Click and update in place using script.aculo.us.

If you step through the tutorial, let us know what you think, and if you know of any other good tutorials you'd like to share, send them our way!

Simple AJAX chat in PHP

Tagged:  

Over at the .NET Butchering (and JAVA messes) blog they have posted a very good tutorial on creating a Chat application in PHP using Ajax. In Web 2.0 social applications chat is very often a desired feature.

Below is an excerpt from the tutorial.

The first thing to be done is creating MySQL tables:



CREATE TABLE `db_name`.`chat_rooms` (

`id` int(10) unsigned NOT NULL auto_increment,

`name` varchar(45) NOT NULL,

`description` text NOT NULL,

`table_name` varchar(45) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;



CREATE TABLE `db_name`.`roomX` (

`id` int(10) unsigned NOT NULL auto_increment,

`date` datetime NOT NULL,

`message` text NOT NULL,

`user` varchar(45) NOT NULL,

PRIMARY KEY (`id`)

) ENGINE=InnoDB DEFAULT CHARSET=latin1;

The first table, chat_rooms, contains a list of all available chat rooms, used to know wich table name will be used for each room. The second one, roomX is a template for a "chat room-like" table: it contains the date (date+time) of each message, the message itself and the user that inputed it (actually it should be an integer, that refers to an appropriate users table, but this is simple version of the script without logging features).

The first thing we're gonna do is execute those SQL scripts (we will be using MySQL and PHP native methods) replacing "roomX" with i.e. "friends_table", and after that we're going to populate the first table, to add an available chat room:



INSERT INTO chat_rooms(name,description,table_name)

VALUES("Friends chat","Comment...","friends_table");

The next step is to compose the "web application". Let's see this picture:

We will use a main page, chat.php, a dinamically reloaded page, room.php and a simple iframe with inside the page sender.php with some controls to post a message.

Let's see chat.php, removing all HTML stuff (like header and formatting, that's up to you):



<?php

session_start();

/* probabily login stuff */

$_SESSION['chat_time'] = $date;

?>

<script type="text/javascript" src="timer.js"></script>

<script type="text/javascript" src="httpRequest.js"></script>

<script language="javascript">

var chatRoomId=<?=$charRoomChoosen?>;

</script>

<body onload="InitializeTimer(); StartTheTimer();">

<div id="chatText" style="overflow:auto;"></div>

<iframe src="sender.php" name="msgFrame"></iframe>

</body>

We'll talk further about the session variable chat_time; I've added 2 javascript scripts: the first one is a simple timer, the second one contains some methods to make HTTP requests.
This is httpRequest.js:



var xmlHttp;



function loadURL()

{

xmlHttp=GetXmlHttpObject()

if (xmlHttp==null)

{

alert ("Browser does not support HTTP Request")

return

}

var url="room.php?chatRoomId="+charRoomId;

xmlHttp.onreadystatechange=stateChanged;

xmlHttp.open("GET",url,true);

xmlHttp.send(null)

}



function stateChanged()

{

if (xmlHttp.readyState==4 xmlHttp.readyState=="complete")

{

/* trim message */

var newlines = xmlHttp.responseText.replace(/^\s+\s+$/g,"");

if(newlines!='')

{

var html = document.getElementById("chatText").innerHTML;

document.getElementById("chatText").innerHTML = html + newlines;

document.getElementById("chatText").scrollTop=20000000;

}



}

}



function GetXmlHttpObject()

{

var xmlHttp=null;

try

{

// Firefox, Opera 8.0+, Safari

xmlHttp=new XMLHttpRequest();

}

catch (e)

{

//Internet Explorer

try

{xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");}

catch (e){xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");}

}

return xmlHttp;

}

This class does an HTTP request (using Firefox, Explorer and other browser Request objects), as I explained in the [Javascript]XML Loading post, and writes the result inside the DIV with id chatText, calling the room.php script (that actually outputs last message sent to the room). The charRoomId used as a parameter of the calling method, is a global variable defined in the chat.php header using a PHP variabile (it should be a $_REQUEST variable).

As we are using asyncronous calls, we need a component that recalls this request periodically. This is the code below (timer.js):



var secs;

var timerID = null;

var timerRunning = false;

var delay = 500;



function InitializeTimer()

{

// Set the length of the timer, in seconds

secs = 1;

StopTheClock();

StartTheTimer();

}



function StopTheClock()

{

if(timerRunning)

clearTimeout(timerID);

timerRunning = false;

}



function StartTheTimer()

{

if (secs==0)

{

StopTheClock();

// Here's where you put something useful that's

// supposed to happen after the allotted time.

// For example, you could display a message:

loadURL();

secs = 1;

timerRunning = true;

timerID = self.setTimeout("StartTheTimer()", delay);

}

else

{

self.status = secs;

secs = secs - 1;

timerRunning = true;

timerID = self.setTimeout("StartTheTimer()", delay);

}

}

This is a timer, called from the chat.php page with onLoad method, that recalls each delay milliseconds the function loadURL() function, defined inside the previous js file.

Now let's see what is inside the chat.php file:



<?php



/* **************** SESSION VARIABLES **************************** */

session_start();



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

{

$_SESSION['chat_time'] = date("Y-m-d H:i:s");

$_SESSION['chat_time_delete'] = time();

}





/************** DB connection ********************+*/

$db_user = "root";

$db_password = "root1";

$db_host ="localhost";

$connection = mysql_connect($db_host,$db_user,$db_password);

mysql_select_db("test",$connection);



/********** RETRIEVES THE NAME OF THE CHAT ROOM TABLE NAME **********/

function getChatTableName($connection,$chatRoomId)

{

/* recupera il nome della tabella della chat room */

$query = "SELECT table_name FROM chat_rooms WHERE id = '".$chatRoomId."'";

$result = mysql_query($query, $connection);

$tableName = NULL;

while($row=mysql_fetch_array($result))

{

$tableName = $row['table_name'];

}



if($tableName==NULL)

{

return NULL;

}



return $tableName;

}



/******************* MESSAGE VISUALIZATION ********************************/





$tableName = getChatTableName($connection,$_REQUEST['chatRoomId']);



if($tableName==NULL)

{

echo "Error selection char room.";

exit();

}

$login_date = $_SESSION['chat_time'];



/* load messages */

$query = "SELECT c.message, c.date, c.user FROM ".$tableName." c WHERE c.date > '".$login_date

."' ORDER BY c.date ASC ";

$result = mysql_query($query,$connection);



$last = "";

while($row=mysql_fetch_array($result))

{

$message = html_entity_decode($row['message']);

echo "[".$row['user']."][".$row['date']."] ".$message." <br/>";

$_SESSION['chat_time'] = $row['date'];

}



/* delete messages older that 60 seconds*/

if((time()-$_SESSION['chat_time_delete'])>60 )

{

$query = "DELETE FROM ".$tableName." WHERE (NOW()-date)>60";

mysql_query($query,$connection);

$_SESSION['chat_time_delete']=time();

}



mysql_close($connection);

?>

We can see session variables initialization: chat_time is the time in which you entered the chat room or of the last message received, while chat_time_delete is the time in which you last deleted a message.
The scripts work this way:

  • connect to the database
  • retrieve the chat room table name using the chatRoomId request variable and the getChatTableName() function
  • query the DB searching for messages not yet received (basing unpon the time of last message received, and at the end of the loop we have a new value for chat_time, that is the last received message time
  • (because) once received messages are useless (a user after connection never received messages of the past), the script delete messages older than 60 seconds

Of course you can format as you like the message board.

At the end we find the sender.php page, that is wrapped in an HTML iframe (because every submission must not cause the entire page reload):



<?php



/***************+ DB variables *****************+*/

$db_user = "root";

$db_password = "root1";

$db_host ="localhost";

$connection = mysql_connect($db_host,$db_user,$db_password);

mysql_select_db("test",$connection);



/********************* NOME TABDELLA CHAT ROOM **************************+*/

function getChatTableName($connection,$chatRoomId)

{

$query = "SELECT table_name FROM chat_rooms WHERE id = '".$chatRoomId."'";

$result = mysql_query($query, $connection);

$tableName = NULL;

while($row=mysql_fetch_array($result))

{

$tableName = $row['table_name'];

}



if($tableName==NULL)

{

return NULL;

}



return $tableName;

}





if($_POST['action']=="send")

if($_SESSION['userid']!="")

{

$tableName = getChatTableName($connection,$_REQUEST['chatRoomId']);



if($tableName==NULL)

{

echo "Error selecting chat room.";

exit();

}



$query = "INSERT INTO ".$tableName."(user,message,date) VALUES(\""

.$_POST['userid']."\",\""

.htmlentities(htmlspecialchars($_POST['message']))."\",NOW())";



mysql_query($query,$connection);



}

?>



<body onload="document.msgForm.message.focus();">



<form name="msgForm" action="sender.php" method="post">

<input type="hidden" value="send" name="action"/>

<input type="hidden" value="1" name="chatRoomId"/>

<input type="text" name="userid" value="<?=($_POST['userid']=="")?"guest":$_POST['userid']?>" size="10" />

<input type="text" name="message" style="width:400px" maxlength="1500"/>

<input type="submit" value="invia"/>

</form>

</body>



<?php

mysql_close($connection);

?>

This page simply prints out a web form (in which users insert their nick name -in this version without a check- and the message) and -consequently to the submission- insert the message in the DB, that will be outputted by the timer.js routine.

This will be your final result:

You can read the full tutorial here.

Hopefully this tutorial will be useful to you.

Syndicate content