Integrate Database Technology in Ajax Development

Source: Internet
Author: User
Tags cdata database issues mysql query
   I. Introduction

Today, many web applications, such as backpack, blinksale, and Gmail, integrate database technology with Ajax. By providing a powerful technology that communicates with the database without refreshing the browser, this integration has a huge impact on web applications and user experience-this means that, you can transmit data in real time while continuing other interactions.

This article will focus on the above technology integration mechanism. It also provides complete reference source code. This example is a simple job record application where each job contains a title, description, and date-allowing users to add, edit, and delete jobs. All these are the basic operations you perform when dealing with database record data, but this application has taken a step further. A role can be changed into an editable form-it will be saved or deleted from the database, and displayed in its new state without refreshing the browser and interrupting user operations.

In this article, I assume that you have a preliminary understanding of Ajax, MySQL, PHP, or a similar server-side language. If you have not created an xml http request object, you can first refer to my article "How to Use Ajax ". Next, let's first discuss the database issues.

2. Create a database

The first thing you need to do is create a database table to store data for these jobs. I created a MySQL table named informit_ajax, which has the ID, title, description, and date fields. These are repeated variables in this article. The following code creates the table:

Create Table 'informit_ajax ′(
'Id' int (11) not null auto_increment,
'Date' datetime not null default '2017-00-00 00:00:00 ',
'Description' longtext not null,
'Title' varchar (100) not null default '',
Primary Key ('id ′)
) Type = MyISAM;

You can use any MySQL query tool or language used to develop applications to execute this code. Once the database is ready, you need to create a front-end file that sends a request to the PHP background.

  3. Send a request

The index HTML file here is a simple data placeholder-it will be analyzed from the database. This file contains references to JavaScript and CSS files. It also contains an onload processor that sends the first request and three Div labels:

· Layout-used to center the page content

· Loading-load the message during the requested data loading, which will be received by the httprequest object

· Posts-used to display job data after each analysis

<Head>
<Title> how to integrate a database with Ajax </title>
<Link href = "CSS/layout.css" rel = "stylesheet" type = "text/CSS"/>
<SCRIPT src = "JS/request. js"> </SCRIPT>
<SCRIPT src = "JS/post. js"> </SCRIPT>
</Head>
<Body onload = "javascript: makerequest ('services/post. php? Method = get'); ">
<Div id = "layout" align = "center">
<Div id = "posts"> </div>
<P> <input type = "button" value = "add a post" onmousedown = "javascript: makerequest ('services/post. php? Method = save '); "/> </P>
<P> <Div id = "loading"> </div> </P>
</Div>

</Body>

The first request is generated when the page is loaded. This request sends a GET request to query a PHP class we will create later. But first, we need to create an analysis method for the request response. The javascript request file is responsible for processing all the basic work, such as creating an object, sending a request, and checking the preparation status. When a response is received from the request object, I use this JavaScript job file to process the HTML generation of these jobs. The onresponse method is quite strong because it processes HTML page generation for each job in two versions: Text and form, and places them in their own custom Div labels; in this way, we can easily locate them during user interaction. In this way, we can switch between the text of each job and the form Version-this can be achieved by clicking an "edit this post" link. The following is the code for the HTML page created for each job. You can see the complete method implementation in the corresponding download source file in this article.

VaR html = "<Div class = 'post' id = 'Post _" + I + "'" + postdisplay + ">"
+ "<Div class = 'title' id = 'title _" + I + "'>" + _ title + "</div>"
+ "<Div class = 'description' id = 'description _" + I + "'>" + _ description + "</div>"
+ "<Div class = 'date' id = 'date _" + I + "'>" + _ date + "</div>"
+ "<A href =/" javascript: toggle ('"+ I +"');/"> edit this post </a> <br/>"
+ "</Div>"
+ "<Div class = 'post' id = 'formpost _" + I + "'" + formpostdisplay + ">"
+ "<Div class = 'title'> <input type = 'text' name = 'title' id = 'formtitle _" + I + "'size = '60' value = '"+ _ title +"'> </div>"
+ "<Div class = 'description'> <textarea type = 'text' id = 'formdescription _" + I + "'Wrap = 'virtual' Cols = '60' rows = '15'> "+ _ description +" </textarea> </div>"
+ "<Div class = 'date'>" + _ date + "</div>"
+ "<Input type = 'button 'name = 'cancel' value = 'cancel' onclick =/" javascript: toggle ('"+ I +"');/">"
+ "<Input type = 'button 'name = 'delete' value = 'delete this Post' onclick =/" javascript: deletepost ("+ _ ID + "); /">"
+ "<Input type = 'button 'name = 'submit 'value = 'Save this Post' onclick =/" javascript: savenewpost ("+ _ ID + ", "+ I +");/">"
+ "</Div>"
+ "<P>" nbsp; </P> ";

The text version of each job simply displays the title, description, date, and a "edit this post" link. The form version of each role has three buttons:

· "Cancel" button-simply switch the job status back to the text version.

· "Delete this post" button-Send the ID of the current job to the PHP Object to delete it from the database.

· "Save this post" button-allows users to save New or edited jobs to the server.

The core methods for processing server request communication include onresponse, savenewpost, deletepost, and getpost, and a getter and setter Method for storing the job index currently being operated. These getter/setter methods provide the current index value to these core methods, so that the correct position can be updated with the correct information based on the index. The following is a brief description and sample code for each core method (which does not include onresponse, because we have observed its functionality before:

· The following savenewpost method collects and sends the form input value to the PHP Object to save the new job and sets the getpost method to onreadystatechange:

Function savenewpost (_ id, _ index ){
VaR newdescription = Document. getelementbyid ("formdescription _" + _ Index). value;
VaR newtitle = Document. getelementbyid ("formtitle _" + _ Index). value;
Setindex (_ index );
Sendrequest ("Services/post. php? Method = save "id =" + _ ID + "" Title = "+ newtitle +" "Description =" + newdescription, getpost );
}

· The following getpost method is a callback method-It updates a separate role when a response is received from a PHP Object:

Function getpost (){
If (checkreadystate (request )){
VaR response = request.responsexml.doc umentelement;
VaR _ Title = response. getelementsbytagname ('title') [getindex ()]. firstchild. Data;
VaR _ description = response. getelementsbytagname ('description') [getindex ()]. firstchild. Data;
VaR _ date = response. getelementsbytagname ('date') [getindex ()]. firstchild. Data;

Document. getelementbyid ("title _" + getindex (). innerhtml = _ title;
Document. getelementbyid ("Description _" + getindex (). innerhtml = _ description;
Document. getelementbyid ("date _" + getindex (). innerhtml = _ date;
Toggle (getindex ());
}
}

· The following deletepost method sends the current index as a request to the PHP Object, which will eventually delete the records in the database and respond to the updated position:

Function deletepost (_ id ){
Sendrequest ("Services/post. php? Method = Delete "id =" + _ id, onresponse );
}

Surprisingly, the most complex part is over. Next let's analyze the most critical part-database interaction.

 4. Interaction with databases

To interact with the database, you need to create methods for searching, inserting, replacing, and deleting roles. I chose to create a post class with the get, save, and delete methods to process these interactions. This class also provides a reference for connecting to a database connection file (used to connect to a database. You must use your own database information instead of logon, password, and database name.

Define ('db _ user', 'username ');
Define ('db _ password', 'Password ');
Define ('db _ host', 'localhost ');
Define ('db _ name', 'database ');
$ DBC = @ mysql_connect (db_host, db_user, db_password) or die ('could not connect to MySQL: '. mysql_error ());

The reference to the connection file and the database name are located in the constructor of this class. Your constructor should look similar to the following code:

Function post (){
Require_once ('mysql _ connect. php ');
$ This-> table = "informit_ajax ";
}

The following dbconnect method is used to create a connection and send the login information to the database. This method is reused in all core methods before the database is queried:

Function dbconnect (){
Define ('link', mysql_connect (db_host, db_user, db_password ));
}

The following get method traverses the database table cyclically. It creates an XML string based on the database row and returns the string to the requester:

Function get (){
$ This-> dbconnect ();
$ Query = "select * from $ this-> table order by ID ";
$ Result = mysql_db_query (db_name, $ query, link );
$ Xml = "<? XML version =/"1.0/" encoding =/"ISO-8859-1/"?> /N ";
$ XML. = "<posts>/N ";
While ($ ROW = mysql_fetch_array ($ result )){
$ XML. = "<post>/N ";
$ XML. = "<ID>". $ row ['id']. "</ID>/N ";
$ XML. = "<date>". $ row ['date']. "</date>/N ";
$ XML. = "<title> <! [CDATA [". $ row ['title']."]> </title>/N ";
$ XML. = "<description> <! [CDATA [". $ row ['description']."]> </description>/N ";
$ XML. = "</post>/N ";
}
$ XML. = "</posts> ";
Mysql_close ();
Header ("Content-Type: Application/XML; charset = UTF-8 ");
Echo $ XML;
}

The following save method achieves two goals by processing the update and Insert Location:

Function save ($ id, $ title, $ description ){
$ This-> dbconnect ();
$ Query = "select * from $ this-> table where id = '$ id '";
$ Result = @ mysql_query ($ query );
If (mysql_num_rows ($ result)> 0)
{
$ Query = "Update $ this-> table set Title = '$ title', description =' $ description', date = now () Where id = '$ id '";
$ Result = @ mysql_query ($ query );
}
Else
{
$ Query = "insert into $ this-> table (title, description, date) values ('$ title',' $ description', now ())";
$ Result = @ mysql_query ($ query );
}
Mysql_close ();
$ This-> get ();
}

The following Delete method deletes a location based on the ID passed as a parameter. Then call the get method to return new data to the request file:

Function Delete ($ id ){
$ This-> dbconnect ();
$ Query = "delete from $ this-> table where id = '$ id '";
$ Result = @ mysql_query ($ query );
Mysql_close ();
$ This-> get ();
}

  5. Comprehensive Application

To integrate the preceding parts, you must create a simple file to serve as a communication bridge between xml http requests and PHP objects. At this time, the page not only creates PHP objects, but also receives queries and passes variables to the dynamically generated method-here it refers to get, save or delete. The following example shows a $ method and a reliable $ id, $ title, and $ description variable.

Require_once ("../classes/post. Class. php ");
$ Post = New post ();
$ Post-> $ method ($ id, $ title, $ description );

We will further discuss these technologies in the future. Today's web development seems to be young and dynamic again, and we are lucky to be part of this new technology era.

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.