Smarty combined with Ajax to achieve no refreshing message _php instance

Source: Internet
Author: User

Read the title you may want to say, message book, very basic Dongdong Ah! Who will not ah, but also to use smarty, this does not look tired? Don't worry, I want to express the idea and structure of a program, not to prove what I do more meaningful, through it I believe that the beginners learn smarty and Ajax some inspiration. Originally used to do with Ajax, unfortunately always debugging unsuccessful, had to use handwritten JS to get, but it does not matter, there is a certain value. Site structure Everyone down the source code to see for themselves, the code is not long, should not look annoyed ^_^, listen to me slowly way.
Now it's all PHP5 oo (object-oriented) is very popular, here is good too, first of all, we use OO to implement database operations and connectivity:
[PHP]
<?php
/**************************

Page: dbclass.php
Author: Boss Fai
Functions: Defining Database Operations Classes
**************************/
?PHP
/**************************

Page: dbclass.php
Author: Boss Fai
Functions: Defining Database Operations Classes
**************************/
class db {
//Create constructors, Function: Database connection and select the appropriate 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 function
Public function query($sql ){
return mysql_query($sql );
}
Get the result set Array function
Public function loop_query($result ){
return mysql_fetch_array($result );
}
//Create destructor, function: Close database connection
Public function __destruct (){
return mysql_close();
}
}
?>
What are the characteristics of this class? First, the next __construct () is a constructor, what is a constructor? The popular point is the function that the class is executed automatically after it is instantiated, what is __destruct ()? is a destructor, it is the role of no way to point to this object, it will automatically destroy the object, which generally contains some finishing operations, such as closing the file, close the database connection methods, see this you do not understand some? That's right! Automatically executes a constructor with a database connection method when the class is instantiated, performs a destructor to close the database connection when the instance is destroyed, and for some basic data operations we just need to new a $db object and then $db->query () ... is not very convenient, of course, this is just a simple example, you can continue to expand. Look at what's inside the config.inc.php:
It's easy, right, interesting. ^_^, look at the template file:

?PHP
/*************************

Page: config.inc.php
Author: Boss Fai
Function: Database parameter variable setting
$dbhost: Host Name
$dbuser: Connection Account
$dbpassword: Connection Password
$dbname: Database name
*************************/
$dbhost = "localhost" ;
$dbuser = "root" ;
$dbpassword = "7529639" ;
$dbname = "TestDB" ;
?>

<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>
<body>
<div align= "Right" id= "check" ></div>
<div id= "Result" ><{* here to display the message content *}>
<{section name=loop loop= $bookinfo}><{* loop Display message *}>
User name: <{$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>
&LT;TD width= "height=" align= "center" > Username:</td>
&LT;TD height= "> <input name=" username "type=" text "class=" username "id=" username "></td>
</tr>
<tr>
&LT;TD width= "height=" align= "center" > Message Content:</td>
&LT;TD height= > <textarea name= "comment" class= "comment" id= "comment" ></textarea></td>
</tr>
</table>
<input type= "button" name= "button" value= "publishes" onclick= "Send (' result '); >
</form>
</body>

The contents of the template in the <{}> will be replaced by PHP, which realizes the art and programmer division of labor, not bad about the content of Smarty also please refer to the manual, here on the inconvenience to say more. Look at the page is how to output the template bar:

?PHP
/*****************************************
Title:smarty with AJAX message Board instance
author:leehui1983 (leader of FAI)
Page Name:index.php
Finish DATE:2006-12-17
*****************************************/

require ('./libs/smarty.class.php '); ///contains Smarty class library
require ('./inc/dbclass.php '); Include database operations class

$db = new db(); //Generate Database Operations instance
$smarty = new smarty(); //Instantiate Smarty Object
$smarty->template_dir = "./templates"; //Set template directory
$smarty->compile_dir = "./templates_c"; Setting up the compilation directory
$smarty->Caching = false; //Set Caching mode
/*****************************************************
Left and right border characters, default to {}, but practical applications are easy to use with JavaScript
Conflict, it is recommended to set <{}> or other.
*****************************************************/
$smarty->left_delimiter = "<{" ;
$smarty->right_delimiter = "}>" ;
$smarty->Assign(' title ',' Smarty with Ajax to make simple message board '); //Replace template content
Set the message content for the initial page to be displayed by Smarty
$rt=$db->query("SELECT * 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 array variables
$smarty->display("INDEX.TPL"); //compile and display the Index.tpl template located under./templates
?>
Page instances of the comment is still more, we refer to the next Smarty Handbook This is so easy!! hehe ~ ~ ~ ~ ~
Next to the introduction of Ajax, here we use a basic development framework to implement, the knowledge of AJAX recommendations to look at the online very popular electronic tutorials Ajax development briefly
var Http_request=false;
function send_request (URL) {//initialization, specifying handler functions, sending requested functions
Http_request=false;
Start initializing the XMLHttpRequest object
if (window. XMLHttpRequest) {//mozilla browser
Http_request=new XMLHttpRequest ();
if (http_request.overridemimetype) {//Set 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, failed to create object instance
Window.alert ("Create XMLHTTP object failed!") ");
return false;
}
Http_request.onreadystatechange=processrequest;
Determine how to send the request, the URL, and whether to execute the next code synchronously
Http_request.open ("Get", url,true);
Http_request.send (NULL);
}
Functions that process return information
function ProcessRequest () {
if (http_request.readystate==4) {//Judge object state
if (http_request.status==200) {//information returned successfully, start processing information
document.getElementById (reobj). Innerhtml=http_request.responsetext;
}
else{//page is not normal
Alert ("The page you requested is not normal!") ");
}
}
}
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 fill in the complete!" </font> ";
return false;
}
else{
Send_request (' checkbookinfo.php?username= ' +username+ ' &comment= ' +comment);
Reobj=obj;
}
}

So we point to "release" button, the data will be sent to the server asynchronous processing, through JS to organize asynchronous updates, after the message you can immediately see your message instead of the traditional waiting page jump, then where the data to deal with it? Look here:
?PHP

/*****************************************
Title:smarty with AJAX Message Board instance
author:leehui1983 (leader of FAI)
Page Name:checkbookinfo.php
Finish DATE:2006-12-17
*****************************************/
Header("CONTENT-TYPE:TEXT/HTML;CHARSET=GBK"); //output code to avoid Chinese garbled
include ('./inc/dbclass.php '); //contains database operations class
$db=new db(); To generate a database operation instance
$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 a message list for real time updates
$arr. = " username : {$rows [' username ']} content: {$rows [' comment ']}<p>];
echo ' username: '. $rows[' username '].' content: '. $rows[' comment '].' <p> ' &NBSP;&NBSP}
   //echo  $arr;

? > 

Well, first insert the data, after the updated data through the JS organization display, Ajax looks really good oh! The general introduction is over, do not know that you have not thought, add an IFRAME can be changed into what? No refresh chat room, play your ability to realize a look. This example uses to Oo,ajax,smarty, the thing is quite many drops, hoped everybody likes, I have decided that this article will contribute to the PHP magazine, everybody if reprint, also wants to indicate the copyright, thanks! Finally, effect chart ~ ~ ~ *

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.