|
|
(text will look like this) |
This is the PHP and AJAX Chat application you create in Chapter 5 of AJAX and PHP: Building Responsive Web Applications.
Online chat solutions have been very popular long before AJAX was born. There are numerous reasons for this popularity, and you’re probably familiar with them if you’ve ever used an Internet Relay Chat (IRC) client, or an Instant Messenger (IM) program, or a Java chat applet.
AJAX has pushed online chat solutions forward by making it easy to implement features that are causing trouble or are harder to implement with other technologies. First of all, an AJAX chat application inherits all the typical AJAX benefits, such as integration with existing browser features, and (if written well) cross-platform compatibilty. An additional advantage is that an AJAX chat application avoids the connectivity problems that are common with other technologies, because many firewalls block the communication ports they use. On the other hand, AJAX uses exclusively HTTP for communicating with the server.
Probably the most impressive AJAX chat application available today is Meebo. We are pretty sure that some of you have heard about it, and if you haven't, we recommend you have a look at it. The first and the most important feature in Meebo is that it allows you to log in into your favorite IM system by using only a web interface. At the time of writing, Meebo lets you connect to AIM or ICQ, Yahoo! Messenger, Jabber or GTalk, and MSN. You can access all these services from a single web page with a user friendly interface, with no pop-up windows or Java applets. Meebo isn't the only web application that offers chat functionality. Even if AJAX is very young, a quick Google search on "AJAX Chat" will reveal several other applications.
It's time to get to work. In the rest of the chapter, we'll implement our own online chat application. We’ll use this occasion to learn about JSON (JavaScript Object Notation), which represents an alternative to XML for representing data exchanged between the web browser and the web server.
JSON is a data format that you can use instead of XML for exchanging information between the JavaScript client and the PHP server script. Interestingly enough, JSON’s popularity increased together with the AJAX phenomenon, although the AJAX acronym implies using XML.
Because XML is a more popular and more widely supported format, we’ve chosed to use XML for all examples in this book, except this one. However, if you like, it’s fairly easy to update the other code samples to use JSON instead of XML. (As you know, this AJAX Chat chapter also has a version that uses XML, and you can compare them to see the differences.)
Perhaps the best short description of JSON is the one proposed by its official website, http://www.json.org: “JSON (JavaScript Object Notation) is a lightweight data-interchange format. It is easy for humans to read and write. It is easy for machines to parse and generate.”
If you’re new to JSON, a fair question you could ask would be: why another data exchange format? JSON, just as XML, is a text-based format that it is easy to write and to understand for both humans and computers. The key word in the definition above is “lightweight.” JSON data structures occupies less bandwitch than their XML versions.
To make an idea of how JSON compares to XML, let’s take the same data structure and see how we would represent it using both standards. In the Chat application you’ll write, the server composes messages for the client that would look like this, if written in XML:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>The same message, written in JSON this time, looks like this:
[As you can see, they aren’t that different. If we disregard the extra formatting spaces that we added for better readability, the XML message occupies 396 bytes while the JSON message has only 274 bytes.
JSON is said to be a subset of JavaScript because it contains two basic struc tures: the object, and the array. An object is an unordered collection of name/value pairs, defined in this form:
{ name1:value1, name2:value2, ... }
The array is an ordered list of values defined in this form:
[ value1, value2, ... ]
The type of the value can be an object, a string, a number, an array, true, false, or null. A string is a collection of Unicode characters surrounded by double quotes. For escaping, we use the backslash.
For more detailed information please refer to http://www.json.org, which covers the theory wonderfully.
It’s obvious that you plan to use JSON, you need to be able to parse and generate JSON structures in JavaScript and PHP. JSON libraries are available for most of today’s programming languages: ActionScript, C, C++, C#, Delphi, E, Erlang, Java, JavaScript, Lisp,Lua, ML and Ruby, Objective CAML, OpenLazslo, Perl, PHP, Python, Rebol, Ruby, Squeak.
For JavaScript, we’ll use the library listed at http://www.json.org/js.html. The direct link to the small JSON libray is: http://www.json.org/json.js. The entire "installation" process consists in copying this file to your application’s folder, and referencing it from the the files that need its functionality.
The JSON solution we’re using for PHP is the library developed by Michal Migurski that can be downloaded from http://mike.teczno.com/json.html. Installing the library implies simply downloading the PHP class file, and copying it into the application’s folder. Next we need to reference it from our application by using the require_once directive like this:
require_once('JSON.php');
In order to effectively start using it, we need to instantiate the class:
$json = new Services_JSON();
Then you’re ready to use it. The encode and decode methods allow us to encode a PHP object into JSON format and to decode a JSON string into a PHP object.
A typical way to build a JSON structure in JavaScript:
var myMessages =The first command defines an object called myMessages, which contains a single member called messages, which at its turn contains an array containg two objects that are made of three members (username, message and color). In order to access the "This is another JSON message" text, you could use the following syntax:
myMessages[0].messages[1].message
The following two code snippets show typical ways to read a JSON structures in JavaScript:
myMessagesJSON = myMessages.toJSONString();or
myMessagesFromJSON = eval ('(' + myMessagesJSON + ') ');The eval function is very fast but it can allow any JavaScript code to be executed, so it’s generally much safer to use the parseJSON method.
In PHP, you encode and decode JSON messages using the encode and decode methods. Let’s take the previous example and do something similar in PHP. A typical way to build a JSON structure in PHP:
require_once('JSON.php');A typical way to read a JSON structure in PHP is:
require_once('JSON.php');This was a preview of Chapter 5 (AJAX Chat) of the AJAX and PHP tutorial, which features even more AJAX web programming examples.
PHP developer? Learn PHP SEO (Search Engine Optimization) techniques. (ASP.NET SEO tutorial forthcoming)