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

Topics:
PHP 101
JavaScript 101
AJAX 101
Jabber (XMPP)

PHP 101

PHP is a very useful language for doing many types of development. Primarily it is used for web development (hence the name, Hypertext Preprocessor) but it is certainly not limited. For our purposes we will be using PHP as both a web development tool and a command line scripting tool (such as how we are using it with the "parseMailScript").

Basic HTML

<html> <!-- Required for all HTML pages -->
	<head> 
		<title>The Top Bar Title</title>
	</head>
	<body>
		Some information
		<!-- A Comment Tag -->
	</body>
</html> <!-- Closing tag, required -->
		
Example 1

Basic HTML with PHP
PHP = Hypertext Preprocessor

<html> <!-- Required for all HTML pages -->
        <head>
                <title>The Top Bar Title</title>
        </head>
        <body>
                Some information
		<br> <!-- A line break -->
                <!-- A Comment Tag -->
		<?  // Denotes the start of PHP processing
        		echo "The Date and Time is: ";  // print a string, end with a semicolon
        		$mydata = "July 29, 2004"; // Assign a variable 
        		echo $mydata; // print the string variable
		?> 

        </body>
</html> <!-- Closing tag, required -->
		
Example 2
Take note of the different comment styles.
The "//" style within PHP and "<--" outside of PHP (normal HTML)
Variables begin with "$".
"=" are assignment.
"echo" is the print function.
";" ends line of code.
PHP files are saved with ".php" not ".html"



Let's make a PHP file that outputs "Hello World!";
		<?PHP
		
		echo("Hello World!\n");
		
		?>
		
As you can see, PHP is very similar to many other languages. There are a bunch of built-in functions (such as echo) and arguments are passed into functions through paranthesis. Strings are put into single or double quotes and the newline char is the \n. Lines of code are ended with semi-colons.

To execute this application, save it as something.php and upload it to a folder in the public_html directory of a server (itp.nyu.edu is probably a good place).

You can execute it browsing to it: http://itp.nyu.edu/~yournetid/foldername/something.php

More Information:
  • PHP: Basic Syntax - Manual


  • Variables

    Variables in PHP are not strictly typed, meaning that you do not have to differentiate between strings, integers and so on. They start with a "$".

    		<?PHP
    			$myString = "hello world\n";
    			echo($myString);
    			$myInteger = 1003;
    			echo($myInteger . "\n");
    			$somethingelse = false;
    			echo($somethingelse . "\n");
    		?>
    		
    More Information:
  • PHP: Types - Manual
  • PHP: Variables - Manual
  • PHP: Constants - Manual


  • Mathematical Operators

    		<?PHP
    			$aValue = 0;
    			$aValue++;
    			echo("aValue now = " . $aValue . "\n");
    			$aValue = $aValue + $aValue;
    			echo("aValue now = " . $aValue . "\n");
    			// % + - * / ++ -- and so on, same as in Processing/Java
    		?>
    		
    More Information:
  • PHP: Expressions - Manual
  • PHP: Operators - Manual


  • Control Structures, Logical Operators and Loops

    		<?PHP
    		
    			// If Statement
    			$aValue = 0;
    			if ($aValue == 0)
    			{
    				echo("aValue is 0");
    			}
    			else if ($aValue == 1)
    			{
    				echo("aValue is 1");
    			}
    			else if ($aValue >= 2)
    			{
    				echo("aValue is greater than or equal to 2");
    			}
    			else
    			{
    				echo("aValue something else");
    			}
    			echo("\n");
    			// Other Logical Operators ==, >, <, >=, <=, ||, &&
    
    		
    			// For loop
    			for ($i = 0; $i < 10; $i++)
    			{
    				echo("\$i = $i\n");
    			}
    			
    			// Also While
    		?>
    		
    More Information:
  • PHP: Control Structures - Manual


  • Arrays and Loops

    		<?PHP
    			// Pretty normal array
    			$anArray = array();
    			$anArray[0] = "Something";
    			$anArray[1] = "Something Else";
    			for ($i = 0; $i < sizeof($anArray); $i++)
    			{
    				echo($anArray[$i] . "\n");
    			}
    			
    			// Key Value Map
    			$anotherA = array("somekey" => "somevalue", "someotherkey" => "someothervalue");
    			$keys = array_keys($anotherA);
    			$values = array_values($anotherA);
    			for ($i = 0; $i < sizeof($keys); $i++)
    			{
    				echo($keys[$i] . " = " . $values[$i] . "\n");
    			}
    		?>
    		
    More Information:
  • PHP: Arrays - Manual


  • Functions

    		<?PHP
    			
    			function myFunction($somearg)
    			{
    				// You would do something here
    				return "You passed in $somearg";
    			}
    			
    			$passing_in = "Hello World";
    			$return_value = myFunction($passing_in);
    			echo($return_value);
    			
    			echo("\n");
    		?>
    		
    More Information:
  • PHP: Functions - Manual


  • Classes and Objects

    		<?PHP
    			class MyClass
    			{
    				var $myClassVar;
    
    				function set_var($new_var)
    				{
    						$this->myClassVar = $new_var;
    				}
    
    				function get_var()
    				{
    						return $this->myClassVar;
    				}
    			}
    	
    			$aClass = new MyClass;
    			$aClass->set_var("something");
    			echo("Var: " . $aClass->get_var() . "\n");		
    		?>
    		
    Classes and Objects in PHP are very similar to Java/Processing. Syntactically though they don't use the "." operator, instead using "->". Also, in the class definition you need to use the "this" keyword.

    More Information:
  • PHP: Classes and Objects - Manual


  • Some Interesting Functions

    isset()
    		<?PHP
    			$somevar = NULL;
    			if (isset($somevar))
    			{
    				echo("somevar is set");	
    			}
    			else
    			{
    				echo("somevar is NOT set");
    			}
    		?>
    		


    More Information:
  • Tons More Here: PHP: Function Reference - Manual


  • JavaScript 101

    JavaScript is a scripting language most often used for client-side web development. It was the originating dialect of the ECMAScript standard.

    (From
    Wikipedia JavaScript)

    ECMAScript is also the standard on which ActionScript 3 (Flash) was developed.

    Essentially JavaScript runs in a browser (raising cross-browser types of issues) that allows pages to be more dynamic and interactive.

    Typically JavaScript is written in the HEAD of an HTML document such as follows:
    <html>
    	<head>
    		<script type="text/javascript"> 
    			alert("Hi There!"); 
    		</script>
    	</head>
    	<body>
    		Nothing here..
    	</body>
    </html>
    		
    It can also be a separate file located on a webserver:
    <html>
    	<head>
    		<script type="text/javascript" SRC="ascript.js"></script>
    	</head>
    	<body>
    		Nothing here..
    	</body>
    </html>
    		
    or both:
    <html>
    	<head>
    		<script type="text/javascript" SRC="ascript.js"></script>
    		<script type="text/javascript"> 
    			alert("Hi There!"); 
    		</script>
    	</head>
    	<body>
    		Nothing here..
    	</body>
    </html>
    		
    Variables

    Defined by "var"
    var avariable; // Declares a variable called avariable
    avarable = 15; // Assigns 15 to that variable
    		
    Variables are not generally "typed".. You can do this:
    var anothervariable = "My Name Is Shawn";
    alert(anothervariable);
    anothervariable = 15;
    alert(anothervariable);
    		
    Comments
    // single line comment
    /* 	
    	multiline 
    	comment 
    */
    		
    Comparison, Conditionals and Loops

    Much the same as other languages you know so I am only giving some examples here:
    var what = true;
    var now = 5;
    
    if (what == now)
    {
    	// Then do this
    }
    else if (1 != 1)
    {
    	// Or this
    }
    else
    {
    	// Those weren't true..  Let's loop
    	
    	for (var i = 0; i < now; i++)
    	{
    		alert("Counting: " + i);
    	}
    }
    		
    Built-In Functions

    We already looked at "alert" and you can see what that does..

    There are a whole slew more (broken down by object): W3Schools: JavaScript Reference (Make it your best friend)

    Creating your own functions

    function dosomething(somedata)
    {
    	var whattosay = "Hi there " + somedata + " , nice to meet you!";
    	alert(whattosay);
    }
    		
    As you can see, the + symbol string concatenation.

    You would run this function with something like this:
    dosomething("shawn");
    
    or
    
    <input type="button" name="name" value="blah" onClick="dosomething(this.value);" />
    		


    As you can see, we can reference the buttons and other objects on the page like divs as if they were JavaScript objects with functions (methods) and properties. You use the "." dot syntax.

    If you use the "id" attribute you have a short-cut available:
    <script type="text/javascript">
    	function changeIt()
    	{
    		var thediv = document.getElementById('mydiv');
    		thediv.innerHTML = "soemthing else";
    	}
    </script>
    My Div:
    <div id="mydiv">Something</div>
    <input type="button" name="changeit" value="Change It" onClick="changeIt();" />		
    		
    My Div:
    Something

    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: The PHP (named ajax_example.php):
    <?php
    	echo "Something";
    ?>
    		
    The HTML (named ajax_example.html):
    <html>
    	<head>
    		<title>AJAX Example</title>
    		<!-- Load up the AJAX External JavaScript file -->
    		<script type="text/javascript" src="ajax.js"></script>
    
    		<!-- Local Javascript Functions and so on -->
    		<script type="text/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.php',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)..	
    			function addOnLoad()
    			{
    				if (window.addEventListener)
    				{
    					window.addEventListener('load', setup_ajax, false);
    				}
    				else if (window.attachEvent)
    				{
    					window.attachEvent('onload', setup_ajax);
    				}
    			}
    			addOnLoad();
    			
    		</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>
    		

    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!

    Jabber/XMPP

    XMPP is the Extensible Messaging and Presence Protocol which Jabber uses.

    Jabber.org
    XMPP Standards Foundation

    It was developed by Jeremie Miller in 1998/1999 and is an open standard based specification for XML based messages. The story is that Jeremie was sick of proprietary chat clients (skype, aim/ichat, msn, yahoo, icq and so on) and having them all open to communicate with those he was working or conversing with. He developed this to be an answer to that issue. It has since become very popular with Google utilizing it for their GTalk service.

    In some ways it is very similar to IRC in that it is distributed among servers and everyone on the network can talk to everyone else by knowing their ID (servers connect to exchange information when needed). In other ways it is more about IM than group chat although group chat is supported well.

    Not just for IM which is presence, buddy list (roster).. Standard XML which can easily be extended for other features.

    Jabber Clients: ichat, google talk, adium and more

    We have a Jabber server installed on asterisk.itp.tsoa.nyu.edu called OpenFire

    Anyone can sign up to use it: Web Signup

    Since Jabber is an open protocol, you can use a myriad of languages to utilize it, opening up tremendous possibilities. We are going to be using the PHP Jabber Client (with some modifications).

    Example - Source