Code for adding and deleting data using Ajax

Source: Internet
Author: User

If you have mastered the previous articles. ajax deletion is easy to implement. what I want to teach you is. use JavaScript and Dom flexibly to achieve a cool Delete effect. you actually learned this. it is clear that in ajax technology, the requested Server Web pages are not very different in non-ajax applications. it is nothing more than accepting requests sent from the front-end. perform some operations in the background! After learning this tutorial, you will understand that you want to achieve a cool ajax effect. You must be proficient in JavaScript Dom.
I just drank too much. The above paragraph was written two days ago. I wanted to go to bed directly. but I want to try it. can I speak better after I drink.
In fact, I think it is better to pass on my knowledge to you when I get drunk. the effect of adding data today is the same as that of adding data in the previous article. however, the delete effect today may have never been seen before. the data to be deleted. click him. click Delete button. this is no different from desktop applications. ajax is such a magic. otherwise, he will not be pursued by Web developers around the world! Let's take a look at the instance first. You will be surprised!
Copy codeThe Code is as follows:
<Html>
<Head>
<Title> ajax allows you to add and delete data without any changes </title>
<Style>
Body {
Font-size: 12px;
}
Table {
Border-collapse: collapse;

}
</Style>
</Head>
<Body>
To make the display smoother, we only read the latest 10 data records in the database. Due to the large number of online testers, we are operating on one database. Concurrency may occur!
<Hr/>
Input content: <input id = "str" type = "input"/> <input type = "button" value = "confirm to add" onclick = "add_Post ()"/>
<Span id = "msg" style = "color: red"> </span>
<Table border = "1"> <! -- This table is used to display data content -->
<Tbody id = "a"> </tbody>
</Table>
<Span style = "color: red"> operation prompt: Click the data you want to delete and click Delete! </Span>
<Input id = "hid_id" type = "hidden"/>
<Input type = "button" value = "delete data" onclick = "del_Data ()"/>
<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 Read (){
Var ajax = ajax_xmlhttp (); // assign the xmlhttprequest object to a variable.
Ajax. open ("post", "Add_Del_Data.asp? Action = read ", true); // sets the request method, the requested webpage, And the url's action parameter is read, 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; // receives the returned data in xml format and stores it in the xmlData variable.
Var list = xmlData. getElementsByTagName ("list"); // obtain all list tags from the returned data.
If (list. length! = 0 ){
Var t = document. getElementById ("a"); // obtain the table that displays the data.
While (t. rows. length! = 0) {// when reading data, if the table has stored rows, all rows will be deleted.
T. removeChild (t. rows [0]);
}
For (var I = 0; I <list. length; I ++ ){
Var tr = t. insertRow (t. rows. length); // Add several rows to the table if there are several lists.
Tr. setAttribute ("id", list [I]. childNodes [0]. firstChild. nodeValue );
Tr. onclick = function (e) {add_Event (e )};
Var td = tr. insertCell (0 );
Td. innerHTML = list [I]. childNodes [1]. firstChild. nodeValue;
}
}
}
}
}
Ajax. send (null); // submit the request. The parameter is null.
}

Window. load = Read ();

Function add_Event (e ){
E = e | window. event;
Var elem = e.tar get | e. srcElement;
If (elem. tagName = "TD "){
Elem = elem. parentNode;
}
Var table = elem. parentNode;
For (var I = 0; I <table. rows. length; I ++ ){
Table. rows [I]. style. background = "";
}
Elem. style. background = "# 999ccc ";
Document. getElementById ("hid_id"). value = elem. id;
}

// Delete data Functions
Function del_Data (){
Var mesage = document. getElementById ("msg"); // retrieves the span that displays the operation information
Mesage. innerHTML = "deleting... please wait ......";
Var table = document. getElementById ("a"); // obtain the table for displaying data
If (table. rows. length = 0 ){
Mesage. innerHTML = "no data in the table can be deleted! ";
Return;
}
Var id = document. getElementById ("hid_id ");
If (id. value. length = 0 ){
Mesage. innerHTML = "You have not selected data! ";
Return;
}
Var ajax = ajax_xmlhttp (); // defines the xmlhttprequest object
Ajax. open ("post", "Add_Del_data.asp? Action = del ", true); // sets the request method, request file, and asynchronous request.

Var param = "id =" + escape (id. value); // obtain the id of the data to be deleted

Ajax. onreadystatechange = function (){
If (ajax. readyState = 4 ){
If (ajax. status = 200 ){
Var xml = ajax. responseXML;
Var msg = xml. getElementsByTagName ("msg") [0]. firstChild. nodeValue;
If (msg = 0 ){
Mesage. innerHTML = "data deleted successfully! ";
Var tr = document. getElementById (id. value); // obtain the currently selected row
Tr. parentNode. removeChild (tr); // reference the parent element of the row. Then delete the row.
Id. value = ""; // Delete the value in the empty text box,
}
If (msg = 1 ){
Mesage. innerHTML = "An error occurred on the server. deletion failed! ";
}
}
}
}
Ajax. setRequestHeader ("content-type", "application/x-www-form-urlencoded ");
Ajax. send (param );
}

// 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_Del_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 max_num = ajax. responseXML. getElementsByTagName ("count") [0]. firstChild. nodeValue;

Var t = document. getElementById ("");
Var tr = t. insertRow (0 );
Tr. setAttribute ("id", max_num );
Tr. onclick = function (e) {add_Event (e )};
Var td = tr. insertCell (0 );
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.
}
</Script>
<A href = "http://www.jb51.net" target = "_ blank"> foot home + </a>
</Body>
</Html>

How is the effect cool? The text box above contains the html source code of the front-end. let's first talk about what we did at the front-end. Let's start with the body tag.


A text of a friendly reminder tells you what will happen!
Text Box and button for adding data! Used to write data to the server database.
A span tag whose ID is msg is used to display information about your current operation.
A table. The table contains a tbody element with the id a. It is used to display the read data. You can select the data to be deleted from the table.
A hidden input box. When you select data, the id value of the data will be put in the input box. This value will be referenced when you delete the data. It will be submitted to the server.
The delete data button defines an onclick event. del_Data () function. It sends a DELETE command to the service.
Enter the script section below. script contains five user-defined functions. ajax_xmlhttp (), Read (), add_Event (), del_Data (), add_Post (). let's explain the functions one by one.

1. ajax_xmlhttp (); Create an available XMLHTTPRequest object. If you do not know what XMLHTTPRequest is, see XMLHTTPRequest.
2. Read (); Read data functions. I have talked about ajax reading data in the previous tutorials. I only want to focus on reading data today. Let's first look at the xml. add_del_data.asp? Action = read. after obtaining all list tags from the xml data returned by the server. the getElementById method is used to obtain the table for storing data. then traverse the list tags cyclically. each list represents a piece of data. each list contains two child elements. 1st sub-elements store the id value of the data, and 2nd sub-elements store the text content of the data. well, let's look at the statements in the for loop in the Read () function:
(1): var tr = t. insertRow (t. rows. length); each cycle of a list will add a row for the table. because each row of the table displays a piece of data. and returns a reference to this row.
(2): tr. setAttribute ("id", list [I]. childNodes [0]. firstChild. nodeValue); set an id attribute for the newly added row. specify a value for this attribute. note: Here is the focus. list [I]. childNodes [0]. firstChild. nodeValue indicates that the value of the id field in each data entry is to be obtained. that is, the id value of the data. we write this value to the id attribute of tr. so that we can reference this id after clicking a line with the mouse.
(3): tr. onclick = function (e) {add_Event (e)}; then bind a user-defined function to the newly added row. The function name is add_Event ();
(4): var td. tr. insertCell (0); adds a new column and returns a reference to this column.
(5): td. innerHTML = list [I]. childNodes [1]. firstChild. nodeValue; in this column, write the text content in the 2nd sub-elements of list I. that is, the content in the content field.
We set the id of each data entry to the id attribute of each row in the table. enter the text in the content of each data entry into the cells in each row. so far, the entire data display process has been completed!
 
3. add_Event (e); this function is bound to each row of the table in the Read function. the closure technique is used to transmit event objects to addEvent. this function is used to find the row you clicked. and obtain the id of the row of data:
(1): e = e | window. event; standardize the event object. FF and other browsers to transmit parameters. IE can directly use window. event.
(2): var elem = e.tar get | e. srcElement; see target or srcElement. elements of the standardized trigger event. the element triggers the event. here, you click the row in the table. but in fact I got TD, not TR. this should be due to the legendary event capture and bubbling. it doesn't matter if we use tagName to determine if it is a TD, take the parent element of the TD. it must be TR. haha.
(3): var table = elem. parentNode; take the parent element of TR. That is, the tbody, and return a reference to the tbody.
(4): Use a for loop to traverse all rows in the tbody. Set the background color of each row to null.
(5): elem. style. background = "#999000"; after the loop is completed, add a background color for the line you clicked.
(6): document. getElementById ("hid_id "). value = elem. id. and write the id of the row you clicked into the text box. id attribute value of this row. it is the id value of the selected data. and each row is clicked. the value in this text box will change with the row you click. the value of this text box is referenced in the submitted delete function.

4. del_Data (); function: Submit the ID of the deleted data to the webpage requested by the server. then, based on the msg tag returned by the server. to determine whether the data is successfully deleted. old rules:
(1): Click Delete to enable the del_Data () function by pressing the delete button. We will first find the span tag with the id msg, and then write an operation message to notify you that the data is being deleted.
(2): Obtain the table to store data. that is, the tbody with id. determine whether data exists in the tbody. if the tbody does not contain any data. no data is available. then exit the function. no further execution.
(3): Obtain the hidden text box and determine whether the text box has a value. If it is empty, a prompt message is displayed. Exit the function. No execution is performed! If a value exists, it indicates that you have selected a data entry. The following ajax will submit the selected data to the server page for deletion.
(4): For details about how ajax submits and recycles data, see "ajax first try to read data" and "ajax read to table ".
(5): del_Data () indicates the msg tag returned by the server. If the content of this tag is 0, it indicates that the server is working smoothly and the data has been deleted successfully.
(6): After the data is successfully deleted: var tr = document. getElementById (id. value); get the selected row.
(7): tr. parentNode. removeChild (tr); // reference the row's parent element tbody and delete the row!
Now the data has been deleted. It is sent back by the server. If the data is deleted successfully, the table row selected by the front-end is deleted. If the data fails, a message is displayed!
5. add_Post (); this function is basically the same as the previous one. submit the added data to the server. the only difference is that after the data is successfully added. we call the Read () function to Read new data. because we must obtain the correct id of the newly added data so that we can delete it correctly!
Now, the front-end code has been explained.
The following is the source code of the server webpage requested in this ajax instance Tutorial:
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 it is "add", add data
Call Add_Data
Case "del" 'if it is del, delete the data
Call Del_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
Response. End


Sub read' defines a process for reading data
Call openconn' open the database link
SQL = "Select top 10 * From del_table order by id desc" 'Open the table named del_table in the database.
Set Rs = Conn. Execute (SQL) 'executes the SQL statement and assigns the index value to the rs variable.

While Not Rs. Eof 'If the table contains data, it will be read cyclically
Xml = xml & "<list>" 'creates a list tag for each piece of data read.
Xml = xml & "<id>" & Rs ("id") & "</id>" 'id field content
Xml = xml & "<content>" & Rs ("content") & "</content>" 'content field content
Xml = xml & "</list>" 'the list tag is closed every time a piece of data is read.
Rs. MoveNext execute the next data read.
Wend' if no data exists in the database, the loop ends.
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 del_table (content) 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.
Else
Xml = xml & "<msg> 1 </msg>" 'if an error occurs, it indicates that an error occurs. Data may fail to be added.
End If
Close_Conn
End Sub

Sub Del_Data 'data deletion Process
On Error Resume Next
OpenConn
Id = Request ("id ")
SQL = "Delete From del_table where id =" & id
Conn. Execute (SQL)
If Err. Number = 0 Then
Xml = xml & "<msg> 0 </msg>"
Else
Xml = xml & "<msg> 1 </msg>"
End If
Close_Conn
End Sub
%>

I used Asp to output xml format data technology on the server. I have explained some of the previous articles. You can easily simulate it using php,. net, and Jsp.
(! -- # Include file = "Conn. asp "--) is my database link file. I will not disclose the database name to ensure security. the table name read this time is: del_table field: ID, Content
Let's talk about this today. If you have any questions, please add the ajax technology exchange group: 110167482
Next article: pagination of ajax Data Reading

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.