- jQuery 1.3 with PHP
- Kae Verens
- 1168字
- 2021-04-01 13:36:00
Quick deletes
Traditionally, web applications worked by sending an entire generated page of HTML to the user, waiting for the user to perform some action, such as a click, and replying with another entire generated page of HTML.
If all that you wanted to do was to delete a single row in a table of hundreds, then it does not make sense to spend time regenerating the hundreds of other rows (database strain), importing and parsing your web templates all over again (hard drive, CPU, and RAM strain), and asking the client to download external resources, such as ads (bandwidth, network lag), all so that you can delete a measly hundred bytes.
The blogging software WordPress is an example of how it should be done. In the control panel for WordPress, whenever a comment is marked as spam or deleted, the comment simply vanishes from the page. The page does not reload.
Unfortunately, most software applications out there are written with just PHP and HTML, and the smallest amount of client-side JavaScript. Those projects are missing out on "wow"ing their users.
To demonstrate quick deletes, consider a list of subscribers to a list in your content management system, as shown in the following screenshot.

Suppose you want to remove Cora Cuddlesby from the list. This is accomplished by clicking the [x] link. Ideally, all that should visually happen is that the Cora Cuddlesby row should vanish.
Using PHP, you would create the list of subscribers, with a link to a deletion page on the [x], and a link to a subscriber profile page on the subscriber name.
Client-side code
Create an HTML file and save it as index.html
in a new directory, /2-quick_deletes
for example. The rest of the files for this example will go in the same directory. In the <body>
of the document, place the following HTML code (the result of your generated list of subscribers):
<html> <head></head> <body> <ul id="subscribers"> <li> <a href="delete.php?id=3">[x]</a> <a href="user.php?id=3">Albertus Ackleton</a> </li> <li> <a href="delete.php?id=6">[x]</a> <a href="user.php?id=6">Bob Burry</a> </li> <li> <a href="delete.php?id=2">[x]</a> <a href="user.php?id=2">Cora Cuddlesby</a> </li> <li> <a href="delete.php?id=5">[x]</a> <a href="user.php?id=5">Derren Drufus</a> </li> </ul> </body> </html>
In the old "web 1.0" fashion, you would then create a delete script, which verifies that you did want to delete that subscriber, then redirects you back after performing the deletion.
That's a round trip that we want to avoid. It takes too long, and involves loading web pages three times, where we should need do it only once.
This is solved by using some Ajax. We want to click on the [x] link, have an "Are you sure?" pop-up message to verify that you clicked the right link, then remove the row directly, without loading a new page.
jQuery is used to replace the [x] links with an Ajax call, which sends the deletion request, and removes the <li>
if it was successful.
Place the following code in the <head>
section of the above HTML:
<script src="/jquery.min.js"></script> <script> function subscribers_init(){ // If an 'x' link is clicked, run delete_subscriber() $('#subscribers li a:first-child') .click(delete_subscriber); } function delete_subscriber(){ var id=this.href.replace(/.*=/,''); this.id='delete_link_'+id; if(confirm( 'Are you sure you want to delete this subscriber?' )) $.getJSON( 'delete.php?ajax=true&id='+id, remove_row ); return false; } function remove_row(data){ if(!data.success)return alert(data.error); $('#delete_link_'+data.id) .closest('li') .remove(); } $(document).ready(subscribers_init); </script>
In the first line, we link to the jQuery library.
Tip
Again, by default, jQuery is called with $
or the jQuery
function (whichever you prefer). In PHP, that would not make sense, as the $
symbol indicates that a variable is being named. However, in JavaScript, $
is just one of the symbols that can be used as part of the actual name of a variable or function, along with the usual letters, numbers, and so on.
Then, the document is told that when it is ready to be manipulated, it should find the first link of each list row in the "subscribers" list, and add an event to each of those so that when it is clicked, the delete_subscriber
function is called.
In delete_subscriber
, an ID is assigned to the link, then the $.getJSON
function is used to send the subscribers' ID to the server. remove_row
is set as the callback function—when the PHP script returns its result, it will be sent as a parameter to remove_row
. Then, the return
false
statement tells the browser not to carry on with the normal HTML link, that is, don't follow the link if the called action returned false
.
The callback in this example is sent a JavaScript object, which was generated on the server and sent to the client using JSON.
if(!data.success)return alert(data.error);
Here, if the callback result is false
, we inform the user of the reported error with an alert box and exit the function.
Otherwise, we use the link's ID to find its closest parent <li>
element and remove it, using the following lines of code:
$('#delete_link_'+data.id) .closest('li') .remove();
Tip
$('#delete_link_'+data.id).closest('li').remove();
is an example of chaining, where multiple operations are performed on the same object, one after the other.
In PHP, this can be done with objects, if each method call returns a reference to the object itself.
Chaining is a very powerful method and can result in very compact code.
The effect of this is that the row disappears, and we can be sure that the server did its job and removed it there.
Server-side code
On the server side, you need to create a script that deletes the subscriber, then returns a verification that the deletion happened.
Here is a sample PHP script, which will return a JSON "yes" message if the subscriber ID is odd, and "no" if the ID is even. You can use it to test the following script—save it as delete.php
.
<?php $id=(int)$_REQUEST['id']; echo ( !($id%2) )? "{'id':$id,'success':1}": "{'id':$id,'success':0,'error':'Could not delete subscriber'}"; ?>
To re-iterate (this is important), there are parts of that JavaScript that you may not have seen before as a PHP developer. The most obvious being the asynchronous nature of .ready
and .getJSON
. In PHP, when you call a function, it is called synchronously, meaning that the script will not carry on to the next line until a result has been returned.
In JavaScript, event and Ajax calls are usually asynchronous, meaning that you call the function, then carry on with the rest of the script. The result will be returned to a callback function, which is disconnected from the original context—it could be called at any time, and will most likely not remember where the original call came from.
Advanced JavaScript writers can use "closures" to remember the context of the call, but that will not be discussed in the first few chapters of the book. At the time of writing, closures don't exist in PHP, although I've seen references to it for 5.3 and up. Closures will be described later in the book, as they are extremely useful.
For simplicity's sake, when writing events and Ajax, you need to remind the callback function what it was supposed to be working on. In the aforementioned case, the PHP script deleted the subscriber, then returned some JSON, which doesn't just say "The deletion worked", but "The deletion of subscriber $id
worked", thus telling the callback function what it should remove from the page.
- 邊做邊學:Photoshop圖像制作案例教程(Photoshop CC 2019·微課版)
- 設計模式之禪(第2版)
- BPEL Cookbook: Best Practices for SOA/based integration and composite applications development
- Oracle SQL Developer 2.1
- Dreamweaver CC實例教程(第5版·微課版)
- 新編AutoCAD 2016從入門到精通
- 中文版Illustrator CC 2018基礎培訓教程
- AutoCAD 2022中文版建筑設計從入門到精通
- 中文版Photoshop CS5平面設計實用教程(第2版)
- 社會調查數據管理:基于Stata 14管理CGSS數據
- MATLAB在日常計算中的應用
- LaTeX論文寫作教程
- Quality Assurance for Dynamics AX-Based ERP Solutions
- HBase企業應用開發實戰
- 管家婆軟件實戰操作教程(輝煌版)