Ajax Add data Instant display information _ajax related

Source: Internet
Author: User
Tags http request
What we're going to learn today is to add data to the server's database using AJAX, and then display the added data instantly without refreshing the page. What needs to be explained is that. The Ajax example tutorial is a 2-point difference from the first 3 articles.
1: We want to operate the database. 2: Replace the requested server page. No longer uses Web_ajax. ASP files. The new request page is: add_data.asp. Look at the suffix everyone should be able to understand. The technology I use on the server is ASP. It is said that ASP is out of date. But his easy to use, easy to learn deeply attracted me! Of course, you can use PHP,. NET, or JSP easily simulate the source code of the ASP file. I will at the end of this tutorial provide the source code for this ASP to everyone!
Let's look at the front end code first. And this Ajax instance effect demo
Copy Code code as follows:

<title>ajax No refresh add data </title>
<body>
Input: <input id= "str" type= "input"/> <input type= "button" value= "OK Add" onclick= "Add_post ()"/>
<span id= "msg" style= "color:red" ></span>
<script type= "Text/javascript" >
function Ajax_xmlhttp () {
Create XMLHttpRequest in IE, suitable for all versions above IE5.0
var msxmlhttp = new Array ("msxml2.xmlhttp.5.0", "msxml2.xmlhttp.4.0", "msxml2.xmlhttp.3.0", "Msxml2.xmlhttp", " Microsoft.XMLHTTP ");
for (var i=0; i<msxmlhttp.length; i++) {
Try
{
_xmlhttp=new ActiveXObject (Msxmlhttp[i]);
}
catch (E)
{
_xmlhttp=null;
}
//loop to create XMLHTTP based on IE browser. end
If not IE browser, create a browser based on Firefox XMLHttpRequest
if (!_xmlhttp && typeof XMLHttpRequest!= "undefined")
{
_xmlhttp=new XMLHttpRequest ();
}
return _xmlhttp;
}

Reading data functions
function Post () {
var ajax = Ajax_xmlhttp (); Assigns a XMLHttpRequest object to a variable.
Ajax.open ("Post", "Add_data.asp?action=read", true);/Set request mode, request file, asynchronous request
Ajax.onreadystatechange = function () {//You can also specify an already-written name
if (ajax.readystate==4) {//data returned successfully
if (ajax.status==200) {//http Request status code returns OK
var xmlData = Ajax.responsexml;
var list = xmldata.getelementsbytagname ("list")//Get all list labels
if (list.length!=0) {
var t = document.createelement ("table");
T.setattribute ("Border", "1");
T.setattribute ("id", "abc"); Set an id attribute for the table, the value is ABC
var thead = T.createthead ();
var _tr = thead.insertrow (0)//Create a row for thead
var _td = _tr.insertcell (0);
_td.innerhtml = "Content";
Document.body.appendChild (t);
for (Var i=0;i<list[0].childnodes.length;i++) {//Traverse all lists, and a few list adds a few lines to the table.
var tr = t.insertrow (0);
var td = Tr.insertcell (0);
td.innerhtml = List[0].childnodes[i].firstchild.nodevalue;
}
}
}
}
}
Ajax.send (NULL);
}

Submit Data function
function Add_post () {
var Msgaes = document.getElementById ("msg");//To display a hint
var str = document.getElementById ("str");//Receive Input
if (Str.value.length = = 0) {
msgaes.innerhtml = "Do not accept empty content!" "
Return
}
Msgaes.innerhtml = "being submitted";
var ajax = Ajax_xmlhttp ();//define XMLHttpRequest Object
Ajax.open ("Post", "Add_data.asp?action=add", true);/Set request mode, request file, asynchronous request

var param = "str=" +escape (str.value);//Get what you entered, notice the STR here, the server will receive the value from Str.
Ajax.onreadystatechange = function () {
if (ajax.readystate==4) {
if (ajax.status==200) {
var msg = ajax.responseXML.getElementsByTagName ("msg");//Get the MSG label returned by the server
if (Msg[0].firstchild.nodevalue = = 0) {
var t = document.getElementById ("abc");
var tr = t.insertrow (0);
var td = Tr.insertcell ();
td.innerhtml = Str.value;
Str.value = "";
msgaes.innerhtml = "Add Complete";
}
else if (Msg[0].firstchild.nodevalue = 3) {
msgaes.innerhtml = "Do not accept empty content";
Return
}
else if (Msg[0].firstchild.nodevalue = 1) {
msgaes.innerhtml = "Error on service side, data add failed!";
Return
}
else{
msgaes.innerhtml = "This instance is for learning to use." Please do not enter maliciously. Thank you! ";
}
}
}
}
Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded");//Note submitting data to the server, you must set the header. Otherwise, the service side will not receive
Ajax.send (param);/Note the Send method submits the contents of the Param variable to the server.
}
Window.load = Post ()//Read data function is not executed until the page is opened or the page is refreshed
</script>
</body>




Click on the example above to view the effect, is what we want to learn today. The above code is just the front end of the HTML code. There are 3 custom functions in the code.


1, Ajax_xmlhttp (); This function we have already talked about in the previous tutorial, is used to create a usability XMLHttpRequest object, if you do not understand, see: Ajax start preparing the article

2, Post (); This function is still used to read data. We no longer explain how Ajax reads data in this chapter of the tutorial. You can see: Ajax preliminary reading data from the AJAX reading to the table but the previous 2 different. The post function is not triggered when you click the button. Instead, the function is executed the first time you open the page or refresh the page. The purpose is to read data that already exists in the database. After the data has been added successfully. The function is not running. One of the secrets in the following explanation I'll tell you! Also look at the settings in the Open method. We have a action=read on the back of the URL we requested, which we should have used. A parameter that is followed by the URL that the server can receive. Use Request.QueryString in ASP to receive. PHP uses the $get method to receive. We set the parameters of this URL to want to tell the server. What we're going to do. There are two custom procedures in the Add_data.asp Web page, one for reading data and one for adding data. This action=read parameter server is received later. The process of reading data is judged!

3, we focus on this add_post function. The function starts by using the getElementById method to find MSG and STR on the Web page. MSG is used to display some of the current operational information. STR is used to get what you have entered. Then determine if you entered content in the str text box. Exits the function if it is empty.
Then look at the setting of the Open method. The parameter behind the requested Web page URL is action=add, and the server-side Web page receives the action parameter. After judging if the value is add, the process of inserting the data is performed.

var param = "str=" +escape (str.value); the contents of the str text box are equal to one STR and then assigned to the Param variable. When the request is sent. Send will submit the contents of this param variable. Escape means encoding String objects so that they can be readable on all computers, decoding what you enter. Testing can sometimes be ignored, but sometimes garbled. For the sake of insurance, we still use escape.

Let's not talk about the program specified by ReadyStateChange. Look below:
Ajax.setrequestheader ("Content-type", "application/x-www-form-urlencoded"); this line means. I want to submit the form content to the server. When your request is post, and the data is submitted to the server. setRequestHeader must be set. If you are using a request with a GET or no data to commit, you can ignore the sentence.

Ajax.send (param), sending a request. and specify the contents of the Param variable to be submitted in the Send argument. You can alert the Param, pop-up str= "What you entered", and then we receive this str on the server's Web page to get the contents of Str. Which is what you typed in the text box. It should be time to take a look at the requested server page. See what he did on the service side. Please see:
Copy Code code as follows:

<!--#include file= "conn.asp"-->
<%
' From: Http://Www.Web666.Net
' Author: Kang Dong
' If you want to reprint, please be sure to keep the above information
' Define a variable to hold the XML data
Xml= "<?xml version= ' 1.0 ' encoding= ' gb2312 '?><body> '"
Action=request.querystring ("action") ' uses Get method to accept an action to determine what the client wants to do
Select Case Action
Case "read" ' If Read is performed
Call Read
Case "Add" if you do add data for add
Call Add_data
Case Else
XML = xml& "<msg> Request parameter error, please do not attempt illegal operation!" </msg> "
End Select

xml=xml& "</body>"
Response.Clear
Response.contenttype= "Text/xml"
response.charset= "gb2312"
Response.Write XML ' pay attention to this sentence. The above ones judge the execution process. The goal is to get a new XML variable content. And then output this XML here
Response.End

Sub read ' defines a process for reading data
Call openconn ' Open database link
SQL = "SELECT * from Web_table" ' opens a table with the name web_table in the database
Set Rs = conn.execute (SQL) ' executes the SQL statement and assigns the SQL index to the Rs variable
XML = xml& "<list>" creates a list label before it starts reading. Include all data under the label
While not rs.eof ' if there is data in the table. The loop reads all the time
XML = xml& "<li>" &rs ("Web") & "</li>"
Rs.movenext ' performs the next reading of a piece of data
Wend ' If there is no data in the database. Then end the loop
XML = xml& "</list>" data read close list label
Close_conn ' Close Database link
End Sub

Sub add_data ' Add data procedure
On Error Resume Next ' If an error continues to execute the program
Openconn ' Open Database link
str = Trim (Request.Form ("str")) ' receives the STR content transmitted by the client
If str = "" Then
XML = xml& ' <msg>3</msg> ' if the content being submitted is empty. Return 3
Exit Sub ' exits procedure
End If
SQL = "Insert into web_table (web) VALUES (' &str& ')"
Conn.execute (SQL) ' Execute Add data
If Err.Number = 0 Then ' To determine if any errors occurred,
XML = xml& "<msg>0</msg>" If no errors occur, the proof data is successful. return 0
Exit Sub
Else
XML = xml& "<msg>1</msg>" If an error occurs. It proves that there is an error. Data is likely to add failure
Exit Sub
End If
End Sub
%>

Above is the server that you use AJAX request page: add_data.asp source code. There should be not much use of ASP now, right? But I am still infatuated with her. Whether you use the service-side technology is php,.net, or JSP and so on. After my explanation you should be able to easily simulate the function of this source code.
The role of 1:include file= "conn.asp" in ASP is to introduce a Web page. conn.asp is my database link file. For security reasons. I will not expose the database name. You build a library of your own. Take a random name and test it.
2: Define a name for an XML variable. Save XML-formatted data in this variable. Use Response.Write to output the contents of an XML variable.
3: Receive the action parameter that you sent over the front-end URL. and determine the value of the action. The Select case doesn't have to be explained. Multiple judgments. If the value of the action is read, the read procedure executes. If it is add, execute the add_data procedure. If neither is the case, the claim is not made through normal channels. Add another MSG label to the XML variable. The output will give a display later
4:response.clear clears the cache.
5:response.contenttype= "Text/xml" defines the text format of the output. XML type
6:response.charset= "gb2312" output encoding, Chinese encoding.
7:response.write XML outputs data from XML variables to the client. This variable holds data in XML format.
8:response.end Stop all output.
9: Define a Read process. Used to read data in a Web field in a Database test_table table. Open the database, SQL statement. Execute SQL. Start reading! I will not speak of this knowledge. And if you don't. I think you should go to learn to operate the database knowledge! I'll focus on the meaning of the read process. Adds the label of a list to the XML variable before reading the data. All the data is then read into the list label, and each piece of data is included in an LI tag. The number of fetches is complete. Closes the list label. What I want to say is that this read process does not output anything to the client. His job is to read the contents of the database in XML format into that XML variable. When the client action=add. Executes the read procedure. The read procedure gives a new XML variable. Response.Write XML Output This variable to the client, the client receives this XML, and we use Responsexml to receive the XML at the front end. And then show! Do you understand? Don't understand, add me q:30458885
10: Let's add_data this process again. The meaning of Add_data is the same as read. is to assign a value to an XML variable after a series of operations are performed. The role of Add_data is to accept data sent by the client. and writes the data to the database. You look carefully at the program logic in the Add_data. First he will judge if the data you submitted is empty. If you add a msg label to an empty XML variable. Content is 3. Then exit Add_data. If the data is not empty. The data is written to the database. Then determine if any errors occurred. If there are no errors, add a msg label to the XML variable, and the content is 0. Represents that everything is fine when writing data. The data was successfully added. The opposite Err.Number is not equal to 0. Indicates an error occurred while writing the data. The data was not added successfully. A msg label is also added to the XML variable. Content is 1. These three cases will exit Add_data immediately after adding the MSG label, regardless of the occurrence. So only one msg tag will be written. Then we'll be right back. The client Add_post function is the one that received the MSG tag. According to the content of MSG to judge what happened to the service side! If the content of MSG is 0, it proves that the server is all right and that no error occurs. The data has been added to the database. We used the DOM to write the contents of STR into the table directly. Does not perform a post function to read data. If MSG content is 3, it proves that you have entered an empty content. If MSG content is 1, it is proved that the server has errors. Data Write Failed!
How do you learn to use AJAX technology to add data to a database? Don't say no! please I speak very hard ...
The next article we say: Ajax modified data display in real time
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.