Smarty uses Ajax to implement a new message book without refreshing

Source: Internet
Author: User

After reading the title, you may want to say that the message book is very basic! No one will, but still use Smarty. Isn't it tiring? Don't worry. What I want to express is a programming idea and structure, instead of proving how meaningful I am. Through it, I believe it is helpful for beginners to learn about Smarty and ajax. Originally done with ajax, but it is a pity that debugging has never been successful, so I had to write JavaScript code. But it doesn't matter, but it still has some value. You can see the source code in the site structure. The code is not long and it should not be annoying.
Now all PHP5 OO (Object Oriented) is very popular, and it is not bad here. First of all, let's take a look at using OO to implement database operations and connections:
[Php]
<? Php
/**************************

Page: dbclass. php
Author: Boss Hui
Function: defines database operations.
**************************/
<? Php
/**************************

Page: dbclass. php
Author: Boss Hui
Function: defines database operations.
**************************/
Class db {
// Create a constructor to connect to the database and select a database
Public function _ construct (){
Require ('config. inc. php ');
Mysql_connect ($ dbhost, $ dbuser, $ dbpassword) or die ("error! ");
Mysql_query ("set names 'gbk '");
Mysql_select_db ($ dbname );
}
// Execute SQL statement Functions
Public function query ($ SQL ){
Return mysql_query ($ SQL );
}
// Obtain the result set number group Function
Public function loop_query ($ result ){
Return mysql_fetch_array ($ result );
}
// Create a destructor to disable database connection
Public function _ destruct (){
Return mysql_close ();
}
}
?>
What are the characteristics of this class? First, we will introduce _ construct () as a constructor. What is a constructor? In layman's terms, the class is automatically executed after being instantiated, __destruct () What is it? It is a destructor. Its function is to automatically destroy an object without any method pointing to this object. It generally contains some final operations, such as closing a file, do you understand how to close the database connection? That's right! The constructor with the database connection method is automatically executed during class instantiation, And the Destructor that closes the database connection when the instance is destroyed, for some basic data operations, we only need to create a new $ db object, and then $ db-> query ()... is it very convenient, of course, this is just a simple example, you can continue to expand. Let's see what is in config. inc. php:
It's easy to be right. If you are interested, let's take a look at ^ _ ^. Let's take a look at the template file:

<? Php
/*************************

Page: config. inc. php
Author: Boss Hui
Function: sets database parameters and variables.
$ Dbhost: Host Name
$ Dbuser: connection account
$ Dbpassword: connection password
$ Dbname: Database Name
*************************/
$ Dbhost = "localhost ";
$ Dbuser = "root ";
$ Dbpassword = "7529639 ";
$ Dbname = "testdb ";
?>

<Html>
<Head>
<Meta http-equiv = "Content-Type" content = "text/html; charset = gbk"/>
<Title> <{$ title}> </title>
<Style type = "text/css">
<! --
. Username {
Height: 20px;
Width: 250px;
}
. Comment {
Height: 100px;
Width: 660px;
}
Body, td, tr {
Font-size: 9pt;
}
-->
</Style>
<Script language = "javascript" src = "./inc/ajax. js"> </script>
</Head>
<Body>
<Div align = "right" id = "check"> </div>
<Div id = "result"> <{* The message content is displayed here *}>
<{Section name = loop = $ bookinfo}> <{* show messages cyclically *}>
Username: <{$ bookinfo [loop]. username}> content: <{$ bookinfo [loop]. comment}> <p>
<{/Section}>
</Div>
<Form method = "post" name = "book" id = "book">
<Table width = "760" border = "1" cellpadding = "0" cellspacing = "0">
<Tr>
<Td width = "80" height = "30" align = "center"> User name: </td>
<Td height = "30"> <input name = "username" type = "text" class = "username" id = "username"> </td>
</Tr>
<Tr>
<Td width = "80" height = "120" align = "center"> message content: </td>
<Td height = "120"> <textarea name = "comment" class = "comment" id = "comment"> </textarea> </td>
</Tr>
</Table>
<Input type = "button" name = "button" value = "publish" onClick = "send ('result');">
</Form>
</Body>
</Html>

The content in the template will be replaced by PHP later in the <{}>, which realizes the division of labor between the artist and the programmer. For more information about Smarty, see the manual, it is inconvenient to say more here. Let's see how the template is output on the page:

<? Php
/*************************************** **
Title: Smarty combined with Ajax message board Instance
Author: leehui1983 (Boss Hui)
Page Name: index. php
Finish Date: 2006-12-17
**************************************** */

Require ('./libs/Smarty. class. php'); // contains the smarty class library
Require ('./inc/dbclass. php'); // contains Database Operation

$ Db = new db (); // generates database operation instances
$ Smarty = new Smarty (); // instantiate a smarty object
$ Smarty-> template_dir = "./templates"; // set Template Directory
$ Smarty-> compile_dir = "./templates_c"; // set the compilation directory
$ Smarty-> caching = false; // sets the cache mode.
/*************************************** **************
Left and right boundary characters. The default value is {}.
Conflict, so it is recommended to set it to <{}> or another.
**************************************** *************/
$ Smarty-> left_delimiter = "<{";
$ Smarty-> right_delimiter = "}> ";
$ Smarty-> assign ('title', 'smarty makes a simple message board with ajax '); // replaces the template content
// Set the initialization Page Message content displayed by Smarty
$ Rt = $ db-> query ("select * from bookinfo order by id desc ");
While ($ rs = $ db-> loop_query ($ rt )){
$ Array [] = array ("username" => $ rs ['username'], "comment" => $ rs ['comment']);
}
$ Smarty-> assign ("bookinfo", $ array );
Unset ($ array); // destroy the array variable
$ Smarty-> display ("index. tpl"); // compile and display the index. tpl Template under./templates
?>
There are still many comments on the page instance. For more information, see Smarty. Manual This is So easy !! Haha ~~~~
Next we will introduce ajax. Here we will use a basic development framework to implement it. I suggest you take a look at the very popular online tutorial ajax development.
Var http_request = false;
Function send_request (url) {// initialization, specifying the processing function and sending the request function
Http_request = false;
// Start initializing the XMLHttpRequest object
If (window. XMLHttpRequest) {// Mozilla Browser
Http_request = new XMLHttpRequest ();
If (http_request.overrideMimeType) {// sets the MIME category
Http_request.overrideMimeType ("text/xml ");
}
}
Else if (window. ActiveXObject) {// IE browser
Try {
Http_request = new ActiveXObject ("Msxml2.XMLHttp ");
} Catch (e ){
Try {
Http_request = new ActiveXobject ("Microsoft. XMLHttp ");
} Catch (e ){}
}
}
If (! Http_request) {// exception. An error occurred while creating the object instance.
Window. alert ("An error occurred while creating the XMLHttp object! ");
Return false;
}
Http_request.onreadystatechange = processrequest;
// Determine the request sending method, URL, and whether to execute the following code synchronously
Http_request.open ("GET", url, true );
Http_request.send (null );
}
// Function for processing the returned information
Function processrequest (){
If (http_request.readyState = 4) {// judge the object status
If (http_request.status = 200) {// The message is returned successfully. Start to process the information.
Document. getElementById (reobj). innerHTML = http_request.responseText;
}
Else {// The page is abnormal.
Alert ("the page you requested is abnormal! ");
}
}
}
Function send (obj ){
Var f = document. book;
Var username = f. username. value;
Var comment = f. comment. value;
If (username = "" | comment = ""){
Document. getElementById (obj). innerHTML = "<font color = red> Please complete it! </Font> ";
Return false;
}
Else {
Send_request ('checkbookinfo. php? Username = '+ username +' & comment = '+ comment );
Reobj = obj;
}
}

In this way, we click the "publish" button, and the data will be processed asynchronously by the server, and asynchronous updates will be organized through JS, after a message is sent, you can immediately see your message instead of waiting for the page Jump. Where can I process the data? Here:
<? Php

/*************************************** **
Title: Smarty combined with Ajax message board instance
Author: leehui1983 (Boss Hui)
Page Name: checkbookinfo. php
Finish Date: 2006-12-17
**************************************** */
Header ("Content-type: text/html; charset = GBK"); // output encoding to avoid Chinese garbled characters
Include ('./inc/dbclass. php'); // contains the database operation class
$ Db = new db (); // generates database operation instances
$ SQL = "insert into bookinfo values (0, '". $ comment. "', '". $ username ."')";
$ Db-> query ($ SQL );
$ Querysql = "select * from bookinfo order by id desc ";
$ Result = $ db-> query ($ querysql );
While ($ rows = $ db-> loop_query ($ result) {// print the message list for real-time update
// $ Arr. =" User Name : {$ Rows ['username']} content: {$ rows ['comment']} <p> ";
Echo 'user name: '. $ rows ['username'].' content: '. $ rows ['comment'].' <p> ';
}
// Echo $ arr;

?>

Well, insert data first, and display the updated data through the JS organization. AJAX looks really good! I just finished the introduction. I don't know if you have thought about it. What can I change it by adding an iframe? Yes! Without refreshing the chat room, you can make full use of your capabilities to achieve a look. This example uses OO, AJAX, SMARTY, and many other things. I hope you will like it. I have decided to contribute this article to the PHP magazine. If you repost it, you also want to indicate the copyright. Thank you! Last ~~~~

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.