11.07.2015 Views

AJAX and PHP

AJAX and PHP

AJAX and PHP

SHOW MORE
SHOW LESS

You also want an ePaper? Increase the reach of your titles

YUMPU automatically turns print PDFs into web optimized ePapers that Google loves.

Chapter 1011. Load http://localhost/ajax/drag-<strong>and</strong>-drop in your web browser <strong>and</strong> test itsfunctionality to make sure it works as expected (see Figures 10.1 <strong>and</strong> 10.2 for reference).What Just Happened?Adding a task is performed as mentioned in the following steps:1. The user enters task.2. When the user clicks on Add this task button or presses Enter, the data is sent to theserver with an asynchronous HTTP request. The server script inserts the new taskinto the database, <strong>and</strong> returns the updated list, which is then injected into the codewith JavaScript.When reordering the list, this is what happens:1. Every task is an XHTML list element: an . The user begins dragging an item; ondropping it, an HTTP request is sent to the server. This request consists of aserialized string of IDs, every list element's ID.2. On the client you'll see the list reordered, while the server updates the order of eachelement in the database.This is how deleting a task works:1. The user drags an item <strong>and</strong> drops it on the DROP HERE TO DELETE area.2. An HTTP request is sent to the server, which performs the task deletion from thedatabase <strong>and</strong> the XHTML element is instantly destroyed.We include in index.php the JavaScript libraries we'll be using:The first line includes our custom functions <strong>and</strong> <strong>AJAX</strong>-related tasks. The second line includes thePrototype library, while the third line includes the script.aculo.us library.The onload event inside the tag calls the startup() function, which defines the unorderedlist with id="tasksList" as a sortable element (Sortable.create). This ensures drag-<strong>and</strong>-dropfunctionality for elements inside the list. The startup() function also defines a droppableelement Droppables.add; we use this as an area where we delete tasks.Also, inside the startup() function, we define a behavior for dropping a list item on the drop zone:onDrop: function(element){var deleteTask = confirm("Are you sure you want to delete this task?")if (deleteTask == true){Element.hide(element);process(element, "delTask");}}249

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!