Example 2: Use jQuery to build a chat program
To demonstrate the power of jQuery, we will build a chat program with ajax function. It allows users to publish information and update information in real time - but there is no page refresh. Given that we are going to deal with a relatively complex application, I will explain the features of jQuery more deeply and show you the functions that are easy to use.
First, let's plan this application. We don't need too much - a front-end, a back-end, and a jQuery library is enough. However, there will be some code to deal with the combination of the front-end and the back-end, so we should first know what we expect to see from the system.
Planning the server side
The backend of this application needs to process the submission and output of information. Keep this in mind so that we can build a sketch for the backend code:
Link to the database
If there is information submission
Insert information into the database
Delete old information
Get information from the database and display it in XML As you can see, it is simple and straightforward. If you need to implement backend programs in another language, you can use this plan to guide you.
Planning a client
The front-end needs to use ajax to process feedback, just like we did in the first example. It needs to process the submission of information and update the chat form continuously with the latest messages. However, we will use another feature - we will use the current UNIX timestamp to show that the message is loaded and just grab this information, thereby reducing loan usage and server load. Here is a sketch of the client planning:
When the page loads
Set the current timestamp to 0 (all information will be submitted after this, for example, all information will be obtained)
Call function to get message
function(function): Get new message
Use POST to send requests to the service
Calling a function to process XML response
Add a timer and call this function once every second (if the server has good performance, this frequency can be increased)
function: XML that converts new message
Set the current timestamp according to the content in the XML
If the status is '2', it means there is no new message and the function call is terminated
Otherwise, each message that is fed back is processed, and the following format is added to the top end of the chat window:
When submitting information:
Use POST to send a request to the server, and you need to specify:
Author name (user specified)
Message body (user specified)
Identify this is a post request
The last timestamp requested from the server
Keep the input text box empty, so that users can enter information here
Call a function that processes XML responses (so that the information is presented in real time)
It looks a bit complicated than the server side, but thankfully with jQuery, the code will not be very long.
Planning a database
We will use the MySql database to store information (although any SQL database can do this, and the code difference is not very large). We need a table with four columns: message id, message author name, message body, and a numeric timestamp. The following SQL code to create this table:
CREATE TABLE `messages` (
`id` int(7) NOT NULL auto_increment,
`user` varchar(255) NOT NULL,
`msg` text NOT NULL,
`time` int(9) NOT NULL,
PRIMARY KEY (`id`)
);
Since we cannot tell how long the message is, we will only use one text field now.
Server-side code (XML)
To establish a backend, we should first know what we need to output from the backend (to determine the interface between the frontend and the backend), and thus work backwards. The following is a simple XML structure:
<?xml version="1.0"?>
<response>
<status>1</status>
<time>1170323512</time>
<message>
<author>John Citizen</author>
<text>Hello world!</text>
</message>
<message>
<author>John Citizen</author>
<text>Hello world again!</text>
</message>
</response>
Note that we have added a tag 'status', which has a value of 1. As I mentioned above, a status value of 1 indicates that the new information request is successful, and 2 indicates that the request is successful but there is no new information. Each message instance includes the author and its information.
Server-side code (php)
Now, back to the server side. We will use php to implement it, but since the output is xml, you can use any language you like to write the later code, such as Perl or Asp. We first define some configuration information so that we can modify it later. We need specific information about the database connection, the number of messages we want to store (the database can process thousands of rows of data, so this can be appropriately set to a larger point), and the number of messages displayed when the user enters the chat room. The code is as follows:
$dbhost = "localhot";
$dbuser = "root";
$dbpass = "";
$dbname = "chat";
$store_num = 10;
$display_num = 10;
Now let's get back to the point, let's continue to look at the backend itself. Database connection is naturally necessary, but we also need to confirm that IE does not cache request data, and we need to confirm that the output format is XML. In order to be able to monitor all errors, we set the error report to "all errors" ("all errors"). To easily manipulate the request data, we set a variable for each parameter in the request, and each variable will take the parameter value in the request as its own value. The code is as follows:
error_reporting(E_ALL);
header("Content-type: text/xml");
header("Cache-Control: no-cache");
$dbconn = mysql_connect($dbhost,$dbuser,$dbpass);
mysql_select_db($dbname,$dbconn);
foreach($_POST as $key => $value)
$$key = mysql_real_escape_string($value, $dbconn);
The foreach statement traverses all POST data, creates a variable for each parameter, and assigns a value to it (for example, path/to/?variable=value will assign $variable as "value"). This simplifies the process of processing requested data without us manually setting it.
Next, we will enter the main function part. Now we process the write of messages to the database, and obtain the corresponding number of messages from the database according to the set display number $display_num. When we were planning the client, I mentioned that when submitting the message, we need to set a response status. We now need to check this response - we assign the value of 'postmsg' to the nibble 'action', indicating that we are processing this check and inserting new data into the database. During processing, we need to insert a new unix timestamp ( timestamp).
However, we still need to clean our database. According to the limitations of your database, you can set the number of stored data. Generally speaking, the use of message logs is not favored, so I set the default storage of 10 messages here. We will use a function to get the id of the latest message and decide whether to delete it. For example, if we add the 11th message, we use 11 to subtract the storage amount (10) to get an id threshold (now 1), so that we can delete all messages less than or equal to this threshold. This example is to delete the first message after all. With sql, we can only write one statement to process these.
The following code snippet checks the 'postmsg' response, adds data to the database, and cleans up the database.
if(@$action == "postmsg")
{
mysql_query("INSERT INTO messages (`user`,`msg`,`time`)
VALUES ('$name','$message',".time().")");
mysql_query("DELETE FROM messages WHERE id <= ".
(mysql_insert_id($dbconn)-$store_num),$dbconn);
}
Developers who use other server-side technologies can write equivalent code. Note that we use the time function to get the unix timestamp. We can assume that this time will not change during SQL execution (even for a very slow server, this code can be executed hundreds of times per second). So when we return a timestamp to the client, we can simply call the time function again, and this value is also trustworthy.
The rest of the work is to process the latest messages from the database and output them in XML. Here we need to use the xml code I wrote above. However, most of the code is SQL. We use the power of SQL to handle this work, and the execution time of the code is not affected. The following are the requirements for SQL query:
It just gets the author and the information
It just gets information that has not been downloaded yet - the client has a last requested timestamp, so this timestamp can be inserted into SQL
The messages need to be sorted so that the latest messages are last, and the reverse order is allowed.
Limit the number of messages obtained based on configuration information.
No one who is familiar with SQL will object to this very simple. The rest is this code. Let's take a look at the query statement first:
$messages = mysql_query("SELECT user,msg
FROM messages
WHERE time>$time
ORDER BY id ASC
LIMIT $display_num",$dbconn);
The remaining code is quite basic. If there is no result, set the status code to 0. Otherwise, set it to 1 to output the initial xml, each message's xml and the final xml. That's all, the code is as follows:
if(mysql_num_rows($messages) == 0) $status_code = 2;
else $status_code = 1;
echo "<?xml version="1.0"?>n";
echo "<response>n";
echo "t<status>$status_code</status>n";
echo "t<time>".time()."</time>n";
while($message = mysql_fetch_array($messages))
{
echo "t<message>n";
echo "tt<author>$message[user]</author>n";
echo "tt<text>$message[msg]</text>n";
echo "t</message>n";
}
echo "</response>";
The final code is in the compressed package, so there is no need to copy the above code. Now that the backend program is completed, we should work more interestingly below - use html and jQuery!
Previous page123Next pageRead the full text