Jquery + Ajax + PHP + MySQL implements Classification List Management (on) and jqueryajax

Source: Internet
Author: User

Jquery + Ajax + PHP + MySQL implements Classification List Management (on) and jqueryajax

In practical applications, we need to manage a customer category to add, delete, and modify customer categories. How can we make these operations more humane, making user operations more convenient has become a topic that we must study.

 

Preparation Phase
You need to have front-end knowledge such as HTML and Jquery, as well as basic PHP programs and MySql database knowledge. To implement the DEMO in this article, you first need a mysql database:

CREATE TABLE `catalist` (  `cid` int(11) NOT NULL auto_increment,  `title` varchar(100) NOT NULL,  `sort` mediumint(6) NOT NULL default '0',  PRIMARY KEY (`cid`) ) ENGINE=MyISAM DEFAULT CHARSET=utf8; 

Next, introduce the jquery library on the page, and the operation result prompts the plug-in jNotify and the deletion confirmation plug-in hiAlert. The latter two plug-ins are described in detail on this site. You can refer to the following link:
Add the files to be prepared to the

<script type="text/javascript" src="js/jquery.js"></script> <script type="text/javascript" src="js/jNotify.jquery.js"></script> <script type="text/javascript" src="js/jquery.alert.js"></script> <script type="text/javascript" src="js/global.js"></script> <link rel="stylesheet" type="text/css" href="css/alert.css" /> 

After preparation, we enter the topic.
Index. php
Index. php is the main page. It reads the category data in the database and displays the data in a list. It also provides buttons for adding, deleting, and modifying data.

<? Php shortde_once ('connect. php '); // connect to the database $ query = mysql_query ("select * from catalist order by cid asc"); while ($ row = mysql_fetch_array ($ query) {$ list. = "<li rel = '". $ row ['cid']. "'> <span class = 'del' title = 'delete'> </span> <span class = 'edit' title = 'edit'> </span> <span class = 'txt '> ". $ row ['title']. "</span> </li>" ;}?>

The code above reads data from the data table and returns a list string. Then we need to output the string to the corresponding list. The Code is as follows:

<Div class = "selectlist"> 

Try to add several data entries to the data table to see a category list.
CSS

.input{width:160px; padding:2px; border:1px solid #d3d3d3} .cur_tr{background:#ffc} .selectlist{width:280px; margin:30px auto; border:1px solid #ccc;} .selectlist h3{height:32px; line-height:32px; padding:0 4px; border-bottom:1px dotted #d3d3d3;  background:#f7f7f7} .selectlist h3 span{float:right; font-weight:500} .selectlist ul{margin-top:4px; margin-left:20px; list-style-type: disc} .selectlist ul li{line-height:26px} .selectlist p{line-height:28px; padding-left:6px} .selectlist ul li span{width:20px; height:20px} .selectlist ul li span.edit{ float:right;background:url(images/edits.gif) no-repeat 0 5px; cursor:pointer} .selectlist ul li span.del,.selectlist ul li span.dels,.selectlist ul li span.cancer{  float:right;background:url(images/del.gif) no-repeat 0 5px; cursor:pointer} .selectlist ul li span.ok,.selectlist ul li span.oks{float:right;background:url(images/ok.gif) no-repeat 0 5px; cursor:pointer} 

I will not explain CSS in detail, but I will understand it after reading it, and the final effect will be displayed.

Add operation
Add the addOpt () function to global. js:

Function addOpt () {var str = "<li> <span class = 'dels' title = 'cancel'> </span> <span class = 'OK' title = 'save'> </ span> <input type = 'text' class = 'input'/> </li> "; $ ("# catalist "). append (str );}

Click the "add item" link to add a new item input box to the DOM.
After the user inputs the content, click "save" to trigger an ajax operation. first look at the Code:

$ (Function () {// Save the Add item $ (". OK "). live ('click', function () {var btn = $ (this); var input_str = btn. parent (). find ('input '). val (); if (input_str = "") {jNotify ("enter a category! "); Return false;} var str = escape (input_str); $. getJSON (" post. php? Action = add & title = "+ str, function (json) {if (json. success = 1) {var li = "<li rel = '" + json. id + "'> <span class = 'del' title = 'delete'> </span> <span class = 'edit' title = 'edit'> </span> <span class = 'txt '> "+ json. title + "</span> </li>"; $ ("# catalist "). append (li); btn. parent (). remove (); jSuccess ("congratulations, operation successful! ");} Else {jNotify (" error! "); Return false ;}});});});

First, obtain the content entered by the user. If no content is entered, the system prompts the user to enter the content, and then encodes the content entered by the user to ensure that Chinese characters can be correctly transmitted to the background program for recognition. Then, the $. getJSON method is used to initiate an asynchronous Ajax request to post. php in the background. Background post. php receives and processes the parameter values. The front-end code responds to the JSON data returned by the background. If the value is added successfully, it appends an item to the List and prompts the user "operation successful ", if it fails, the system prompts the user "error ".
To cancel the Add item operation, you only need to click the cancel button and execute the following code:

// Cancel the Add item $ (". dels "). live ('click', function () {$ (this ). parent (). remove (); // remove new items });

Post. php In the background needs to process the new item content. The Code is as follows:

Include_once ('connect. php '); // connect to the database $ action =$ _ GET ['action']; switch ($ action) {case 'add ': // Add an item $ title = uniDecode ($ _ GET ['title'], 'utf-8'); $ title = htmlspecialchars ($ title, ENT_QUOTES ); $ query = mysql_query ("insert into catalist (cid, title) values (NULL, '$ title')"); if ($ query) {$ insertid = mysql_insert_id ($ link); $ arr = array ('id' => $ insertid, 'title' => $ title, 'success' => 1 );} else {$ arr = array ('success '=> 2);} echo json_encode ($ arr); break; case '': break ;}

After receiving the content submitted by the front-end, decode it, write it to the data table, and output the JSON data format for foreground processing. For the uniDecode () function, you can download the source code to read and parse the Chinese string submitted by jquery asynchronously.
The add item operation has been completed. See the delete item operation below. Delete an item
Return to global. js and add the following code to $ (function:

// Delete an item $ (". del "). live ('click', function () {var btn = $ (this); var id = btn. parent (). attr ('rel '); var URL = "post. php? Action = del "; hiConfirm ('Are you sure you want to delete it? ',' Hint ', function (r) {if (r) {$. ajax ({type: "POST", url: URL, data: "id =" + id, success: function (msg) {if (msg = 1) {jSuccess ("deleted successfully! "); Btn. parent (). remove () ;}else {jNotify (" operation failed! "); Return false ;}}});}});});

Obviously, by clicking the "delete" button, you can also post to the background. php sends an ajax request, sends the parameter ID corresponding to the deleted item to the background, and responds to the background processing result. If the request succeeds, the user is prompted to "delete successfully" and remove () remove the data item. If the data item fails, the system prompts "operation failed ".
The backend post. php receives parameters and processes them accordingly:

Case 'del ': // delete item $ id = $ _ POST ['id']; $ query = mysql_query ("delete from catalist where cid = ". $ id); if ($ query) {echo '1';} else {echo '2';} break;

The preceding code snippet is added to the switch statement of post. php. The delete statement is executed and the execution result is output for front-end processing.
The modification operation will be explained in the next article. Stay tuned and do not miss it.

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.