Realization of real-time data transmission with AJAX integrated database technology

Source: Internet
Author: User
Tags add connect mysql mysql query variables php class string version
ajax| Data | Database One, INTRODUCTION

Today, there are quite a few web applications, such as Backpack,blinksale and Gmail, that integrate database technology with Ajax. This integration has a huge impact on Web applications and the user experience by providing a powerful technology that communicates with the database without refreshing the browser-which means that real-time data transfer can be achieved while the user continues to interact with others.

This article will focus on the above technology integration mechanism. At the same time provide a complete reference source. This example is a simple job record application where each job contains a title, description, and date-allowing users to add, edit, and delete titles. All of this is a basic operation when dealing with database data, but the application is a step closer. A job can be changed into an editable form-it will be saved or deleted from the database and displayed in its new state without the need to refresh the browser and break the user's action.

In this article, I assume you have a rudimentary understanding of Ajax, MySQL and PHP, or a similar server-side language. If you have not created an XML HTTP request object, you can refer to my article "How to use Ajax" first. Next, let's start with the database issue.

Second, create a database


The first thing you need to do is create database tables to store data for these jobs. I created a MySQL table called Informit_ajax-it has id,title,description and date fields-these are the variables that are recurring in this article. The following is the code that creates the table:

CREATE table′informit_ajax′ (
′id′int (one) not NULL auto_increment,
′date′datetime not NULL default ' 0000-00-00 00:00:00 ',
′description′longtext not NULL,
′title′varchar not NULL default ',
PRIMARY KEY (′id′)
) Type=myisam;

You can execute this code using any MySQL query tool or the language used to develop the application. Once you have the database ready, you will need to create a front-end file that makes requests to the PHP background.

   Iii. issue of requests

The indexed HTML file here is a simple data placeholder-it will be parsed from the database. This file contains references to JavaScript and CSS files, as well as an OnLoad processor and three div tags for the first request:

· Layout-is used to center the content of the page

· loading-loads the message during the requested data load, which will be received for the HttpRequest object

· Posts-is used to display job data after each analysis


integrate a Database with AJAX











The first request is generated when the page is loaded. This request sends a GET query to a PHP class that we will create later, but first we need to create the profiling method for the response of the request. JavaScript request files are responsible for all basic work, such as creating objects, sending requests, and checking readiness status. When I receive a response from the request object, I use this JavaScript job file to handle the HTML generation of these positions. The onresponse approach is pretty strong because it generates HTML pages for each job with text and form versions, and places them in their own custom div tags, so that we can easily locate them during user interaction. In this way, we can switch between the text of each job and the version of the form-this can be done by clicking on an "edit this post" link. Here is the code for the HTML page created for each job, and 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= ' value= '" "+ _title +" "" "</div>"
+ "<div class= ' description ' ><textarea type= ' text ' id= ' formdescription_ ' + i +" ' wrap= ' virtual ' cols= ' ' rows= ' 15 ' "+ _ Description + "</textarea> </div>"
+ "<div class= ' Date '" + _date + "</div>"
+ "<input type= ' button ' name= ' Cancel ' value= ' Cancel ' + i +" '); " >
+ "<input type= ' button ' name= ' delete ' value= ' delete this post ' + _id +"); " >
+ "<input type= ' button ' name= ' Submit ' value= ' Save this post ' + _id +", "+ i +"); " >
+ "</div>"
+ "<p>" nbsp; </p>;

The text version of each title simply displays the title, description, and date and an "edit this post" link. There are three buttons for each job's form version:

·" Cancel button-simply switches the status of the position back to the text version.

·" Delete this post button-sends the ID of the current job to the PHP object to remove it from the database.

·" Save this post button-allows the user to save a new or edited title to the server.

The core methods for handling server-side request traffic are onresponse,savenewpost,deletepost and Getpost methods, as well as a getter and a setter method that stores the job index for the current operation. These getter/setter methods provide the current index value to these core methods, so that the correct job can be updated with the correct information based on the index. Here's a short description and code example for each of the core methods (excluding Onresponse, because we've seen it before):

· The following Savenewpost method saves the new title by collecting and sending the form input value to the PHP object and sets the Getpost method to the callback method of the 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 that is responsible for updating a separate title when a response is received from a PHP object:

function Getpost () {
if (checkreadystate (request)) {
var response = Request.responseXML.documentElement;
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 eventually deletes the records in the database and responds with an updated title:

function Deletepost (_id) {
SendRequest ("Services/post.php?method=delete" "id=" + _id, onresponse);
}


Surprisingly, the most complicated part is over. Let's analyze the most critical part-database interaction.

Iv. interacting with the database

In order to interact with the database, you need to create methods for retrieving, inserting, replacing, and deleting titles. I chose to create a post class with Get,save and delete methods to handle these interactions. This class also has a reference to the database connection file (used to connect to the database). You must use your own database information instead of the login, 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 name of the database is in the constructor of the 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 responsible for creating the connection-by transferring the login information to the database; This method is used in all the core methods before querying the database:

function Dbconnect () {
DEFINE (' LINK ', mysql_connect (Db_host, Db_user, Db_password));
}

The following get method loops through the database table, 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 = " \n";
$xml. = " \ n";
while ($row = Mysql_fetch_array ($result)) {
$xml. = " \ n";
$xml. = " ". $row [' id ']. " \ n";
$xml. = " ". $row [' Date ']. " \ n";
$xml. = " ! [cdata[]. $row [' title ']. "]]> \ n";
$xml. = " ! [cdata[]. $row [' description ']. "]]> \ n";
$xml. = " \ n";
}
$xml. = " ";
Mysql_close ();
Header ("Content-type:application/xml; Charset=utf-8 ");
Echo $xml;
}

The following Save method implements two purposes by handling 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 is responsible for deleting a location based on the ID passed as a parameter. Then call the Get method to return the 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 ();
}

   v. Comprehensive application

To integrate these parts together, you need to create a simple file to assume the communication bridge between the XML HTTP request and the PHP object. The page not only creates PHP objects, but also receives the query and passes the variables to the dynamically generated method-this refers to Get,save or delete. The following example query includes a $method and reliable $id, $title, and $description variables.

Require_once (".. /classes/post.class.php ");
$post = new post ();
$post-> $method ($id, $title, $description);

We will discuss these technologies further later. Today's web development seems to be young and vibrant again, and we are fortunate 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.