开发者

CRUD methods with PHP, JS/jQuery, and a little AJAX

I've been working on a system where you can create-read-update-delete to/from a table in a SQLite database. So far I've only written the create and view methods (easy).

Now, I have ran into a roadblock on deciding how to go about deleting and updating items. On the view page, there is query to the database through php and a generation of the table (echoed through php into html). There is also a button added next to each row that looks like a little trash can to delete the row.

How can I use AJAX to simultaneously delete the row from the html table and sqlite table? A more definitive question would be, how开发者_如何学JAVA can I link each button to each row and query the database when the button is clicked?

Here is the generated table:

foreach($result as $entry){
 echo  '<tr>' . '<td>'. $entry['department']. ' ' . $entry['CRN']. '</td>' . 
    '<td>'. $entry['title'] . '</td>' . 
    '<td>'. $entry['addDate'] . '</td>'. 
    '<td><button class="fg-button fg-button-icon-left ui-state-default ui-corner-all"><span class="ui-icon ui-icon-trash"></span></button></td>'.'</tr>';
}


  1. Create a PHP controller and action. It has to take an ID as a parameter and it should execute a delete command against your database using that ID. Ideally, it will accept only DELETE requests (not GET or POST). This isn't always possible because some browsers don't support DELETE HTTP requests.
  2. on your front end, create HTML and javascript that looks like this:

HTML:

<input id="clickMe" type="button" value="Delete Button" data-rowId="12"/>

Javascript:

$(document).ready(function(){
    $('#clickMe').click(function(){
        // send the delete request
        $.ajax({
            url: '/myEntity/delete',
            data: {id: $(this).data('rowId')},
            type: 'DELETE',
            // removes the row only if the delete succeeds
            success: function(){ $(this).parents('tr').remove(); }
        });
    });
});

Change type: 'DELETE' to type: 'POST' if you're working with browsers that don't support DELETE.


You could have the Ajax call return the new list of values and just replace the entire table with the new content.

  • In the JS, make delete call with a callback.
  • In the callback:

    • empty the div that contains the table
    • create a new table based on the results of the call (by making a call to PHP if that's what's generating the table)
    • append that table to the div

That's something we do often, although, we need to since it's a multi-user system.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜