Ajax add real-time data display information

Source: Internet
Author: User

What we want to learn today is: Use ajax to add data to the database on the server, and then instantly display the added data without refreshing the webpage. it must be noted that. this ajax instance tutorial differs from the first three.
1: We want to operate the database. 2: Change the requested server webpage. no longer use the Web_ajax.Asp file. the new request webpage is Add_Data.Asp. you can understand the suffix. the technology I use on the server is Asp. asp is outdated. however, his ease of use and easy to learn have deeply attracted me! Of course, you can also use php,. net, or jsp to easily simulate the source code of the Asp file. I will provide the source code of this Asp file to you at the end of this tutorial!
Next let's take a look at the front-end code and the demo of the ajax instance. Copy codeThe Code is as follows: <Head>
<Title> ajax does not add any new data </title>
</Head>
<Body>
Input content: <input id = "str" type = "input"/> <input type = "button" value = "confirm to add" onclick = "add_Post ()"/>
<Span id = "msg" style = "color: red"> </span>
<Script type = "text/javascript">
Function ajax_xmlhttp (){
// Create xmlhttpRequest in IE for all IE5.0 and later versions
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;
}
} // Cyclically create xmlhttp. End Based on IE browser
// If not, create xmlhttpRequest Based on FireFox and other browsers
If (! _ Xmlhttp & typeof XMLHttpRequest! = "Undefined ")
{
_ Xmlhttp = new XMLHttpRequest ();
}
Return _ xmlhttp;
}

// Read data Functions
Function Post (){
Var ajax = ajax_xmlhttp (); // assign the xmlhttprequest object to a variable.
Ajax. open ("post", "add_data.asp? Action = read ", true); // sets the request method, request file, and asynchronous request.
Ajax. onreadystatechange = function () {// You can also specify a name for the function that has been written.
If (ajax. readyState = 4) {// data returns success
If (ajax. status = 200) {// Return OK for the http Request status code
Var xmlData = ajax. responseXML;
Var list = xmlData. getElementsByTagName ("list"); // obtain all list tags
If (list. length! = 0 ){
Var t = document. createElement ("table ");
T. setAttribute ("border", "1 ");
T. setAttribute ("id", "abc"); // set an id attribute for the table with the value 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 the lists, and add several rows to the table if there are several lists.
Var tr = t. insertRow (0 );
Var td = tr. insertCell (0 );
Td. innerHTML = list [0]. childNodes [I]. firstChild. nodeValue;
}
}
}
}
}
Ajax. send (null );
}

// Data submission Function
Function add_Post (){
Var msgaes = document. getElementById ("msg"); // displays the prompt information.
Var str = document. getElementById ("str"); // receives the input content
If (str. value. length = 0 ){
Msgaes. innerHTML = "Empty content is not accepted! "
Return;
}
Msgaes. innerHTML = "submitting ";
Var ajax = ajax_xmlhttp (); // defines the xmlhttprequest object
Ajax. open ("post", "add_data.asp? Action = add ", true); // sets the request method, request file, and asynchronous request.

Var param = "str =" + escape (str. value); // obtain your input content. Note that the str here will receive the value in str.
Ajax. onreadystatechange = function (){
If (ajax. readyState = 4 ){
If (ajax. status = 200 ){
Var msg = ajax. responseXML. getElementsByTagName ("msg"); // obtain the msg tag 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 = "added ";
}
Else if (msg [0]. firstChild. nodeValue = 3 ){
Msgaes. innerHTML = "do not accept empty content ";
Return;
}
Else if (msg [0]. firstChild. nodeValue = 1 ){
Msgaes. innerHTML = "An error occurred on the server and data addition failed! ";
Return;
}
Else {
Msgaes. innerHTML = "this instance is used for learning. Please do not enter it maliciously. Thank you! ";
}
}
}
}
Ajax. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); // you must set this header to submit data to the server. otherwise, the server will not receive
Ajax. send (param); // note that the send method submits the content in the param variable to the server.
}
Window. load = Post (); // The Data Reading function is executed only after the webpage is opened or refreshed.
</Script>
</Body>
</Html>

Click the above to view the instance effect, which is the purpose of learning today. The above code is only the front-end html code. There are three custom functions in the code.

1. ajax_xmlhttp (); this function is used to create an availability XMLHTTPRequest object as described in the previous tutorial. If you do not know about it, see ajax preparation.

2. Post (); this function is still used to read data. in this chapter, we will not explain how ajax reads data. you can refer to: ajax first try to read data and ajax read data to the table, but the first two are different. this Post function is not triggered when you click the button. this function is executed only when you open or refresh the page for the first time. it is used to read existing data in the database. after the data is added successfully. this function is not run. I will tell you the following explanation of the secret! In addition, let's take a look at the settings in the open method. we have added an action = read next to the requested URL, which should have been used. the parameter following the url. The server can receive this parameter. use Request. queryString to receive. use the $ get method in Php to receive messages. we set this url parameter to tell the server. what actions should we perform. there are two custom processes in the Add_Data.Asp webpage, one for reading data and the other for adding data. this action = after the read parameter is received by the server. the process of reading data is determined!

3. Let's focus on this add_Post function. at the beginning, the function used the getElementById method to search for msg and str on the webpage. msg is used to display some current operation information. str is used to get the content you entered. then determine whether you have entered the content in the str text box. exit the function if it is null.
Let's look at the setting of the open method. The parameter after the requested webpage url is action = add. The server webpage receives the action parameter. If the value is "add", the data is inserted.

Var param = "str =" + escape (str. value); the content of the str text box is equal to one str, and then assigned to the param variable. when a request is sent. send will submit the content in this param variable. escape refers to encoding String objects so that they can be read on all computers, that is, decoding your input content. some tests may ignore these errors, but sometimes garbled characters may occur. for the sake of insurance, we still use escape.

Let's not talk about the program specified by readystatechange. Let's look at the following:
Ajax. setRequestHeader ("content-type", "application/x-www-form-urlencoded"); this line indicates. I want to submit the form content to the server. when your request is post and data is submitted to the server. setRequestHeader must be set. if you use get or no data to submit a request, you can ignore this sentence.

Ajax. send (param); send the request. specify the content in the param variable to be submitted in the send parameter. you can alert param, and str = "your input content" will pop up. Then, we can get the content in str by receiving this str on the webpage of the server. this is what you entered in the text box. it is time to check the requested server webpage. let's see what he did on the server. see:Copy codeThe Code is as follows: <! -- # Include file = "Conn. Asp" -->
<%
'From: http://Www.Web666.Net
'Author: Kang Dong
'The above information must be retained if reprinted
'Define a variable to save xml data.
Xml = "<? Xml version = '1. 0' encoding = 'gb2312 '?> <Body>"
Action = Request. QueryString ("action") 'accepts an action in get to determine what operations the client wants to perform.
Select case action
Case "read" 'if it is read, the data read operation is performed.
Call Read
Case "add" 'if this parameter is set to add, add data
Call Add_Data
Case else
Xml = xml & "<msg> the request parameter is incorrect. Please do not try to operate it illegally! </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 judgment execution process aims to get a new xml variable content, and then output this xml
Response. End

Sub read' defines a process for reading data
Call openconn' open the database link
SQL = "Select * From web_table" 'Open the table named web_table in the database.
Set Rs = Conn. Execute (SQL) 'executes the SQL statement and assigns the index value to the rs variable.
Xml = xml & "<list>" 'create a list label before reading. All data is included under this label.
While Not Rs. Eof 'If the table contains data, it will be read cyclically
Xml = xml & "<li>" & Rs ("web") & "</li>"
Rs. MoveNext execute the next data read.
Wend' if no data exists in the database, the loop ends.
Xml = xml & "</list>" 'closed list tag after Data Reading
Close_conn' close the database link
End Sub

Sub Add_Data 'add Data Process
On Error Resume Next 'if an Error occurs, continue executing the program
Openconn' open the database link
Str = Trim (Request. Form ("str") 'receives str content from the client.
If str = "" Then
Xml = xml & "<msg> 3 </msg>" 'If the submitted content is empty, 3 is returned.
Exit Sub 'exit
End If
SQL = "Insert Into web_table (web) values ('" & str &"')"
Conn. Execute (SQL) 'Run to add data
If Err. Number = 0 Then 'to determine whether an error has occurred,
Xml = xml & "<msg> 0 </msg>" 'if no error occurs, the data is successful. 0 is returned.
Exit Sub
Else
Xml = xml & "<msg> 1 </msg>" 'if an error occurs, it indicates that an error occurs. Data may fail to be added.
Exit Sub
End If
End Sub
%>

The above is the source code of the server webpage you requested using ajax: Add_Data.Asp. Should Asp be used less now? But I am still infatuated with her. No matter whether you use the server-side technology such as Php,. Net, or Jsp, after my explanation, you should easily simulate the source code function.
1: include file = "Conn. asp is used to introduce a webpage in Asp. conn. asp is the link file of my database. for security. I will not expose the database name. create a database by yourself. start a test by name.
2: Define a variable named xml. Save the data in xml format in this variable. Use Response. Write to output the content in the xml variable.
3: receive the action parameter you passed in the front-end url. and determine the value of the action. select case does not need to be explained. multiple Identification. if the value of action is read, The Read process is executed. if it is add, the Add_Data process is executed. if neither of them indicates that the request is not made through a normal channel. add another msg label to the xml variable. the output will show the displayed content.
4: Response. Clear cache.
5: Response. ContentType = "text/xml" defines the output text format. xml type
6: Response. CharSet = "gb2312" output encoding, Chinese encoding.
7: Response. write xml outputs the data in the xml variable to the client. The variable stores the data in xml format.
8: Response. End stop all output.
9. Define a Read process. It is used to Read data in the web field in the test_table table of the database. Open the database, and run the SQL statement. Execute the SQL statement to start reading! I will not talk about this knowledge. If you do not, I think you should learn about database operations! I will focus on the significance of this Read process. before reading data, add a list label to the xml variable. then, all the data is read to the list tag, and each data is contained in a li tag. the number is read. close the list tag. I want to say that this Read process does not output any content to the client. his job is to read the content in the database to the xml variable in xml format. when the client action = add. execute the Read process. the Read process provides a new xml variable. response. write xml outputs this variable to the client. The client accepts this xml and we use responseXML at the front end to receive this xml. then display! Do you understand? I don't understand how to add Q: 30458885
10: Let's talk about the Add_Data process. the meaning of Add_Data is the same as that of Read. all values are assigned to xml variables after a series of operations are performed. add_Data is used to receive data sent from the client. and write the data to the database. take a closer look at the program logic in Add_Data. first, he will determine whether the data you submitted is empty. if it is null, add a msg label to the xml variable. the content is 3. then exit Add_Data. if the data is not empty. write the data to the database. then determine whether an error has occurred. add a msg label to the xml variable if there are no errors. The content is 0. it indicates that everything works normally when writing data. the data is successfully added. opposite Err. number is not equal to 0. an error occurs when writing data. the data is not successfully added. at this time, a msg tag will be added to the xml variable. the content is 1. in either case, the Add_Data will be exited immediately after the msg label is added. therefore, only one msg tag will be written. then we will immediately return to the client's Add_Post function. After receiving the msg label, you can determine what happened on the server based on the msg content! If the content of msg is 0, it indicates that everything on the server is normal and no error occurs. the data has been added to the database. we directly use Dom to write the content in str into the table. no Post function is executed to read data. if msg content is 3, it indicates that you have entered an empty content. if the msg content is 1, it indicates that an error occurs on the server. data Writing failed!
How do you learn to use ajax technology to add data to a database? Do not say No! Please, I am working very hard ......
Next article: real-time display of ajax data modification

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.