PHP MySQL Inline Editing using jQuery Ajax
PHP MySQL Inline Editing using jQuery Ajax
Last modified on March 8th, 2017 by Vincy.
In this tutorial, we are going to see about PHP inline editing using jQuery AJAX. Inline editing will make user effort simple by allowing editing in the list view itself. We need not let users navigating to a separate page showing edit form.
In this example, we are using HTML table to list database results. We add the contentEditable attribute to the table cells to allow inline editing on clicking cell view. Previously in AJAX Add Edit Delete tutorial, we have done the same by using jQuery show/hide.
HTML Editable Content
The following HTML code is used to show editable table to the user. We call jQuery on the blur event of the editable cell by passing cell data.
<table class="tbl-qa"> <thead> <tr> <th class="table-header" width="10%">Q.No.</th> <th class="table-header">Question</th> <th class="table-header">Answer</th> </tr> </thead> <tbody> <?php foreach($faq as $k=>$v) { ?> <tr class="table-row"> <td><?php echo $k+1; ?></td> <td contenteditable="true" onBlur="saveToDatabase(this,'question','<?php echo $faq[$k]["id"]; ?>')" onClick="showEdit(this);"><?php echo $faq[$k]["question"]; ?></td> <td contenteditable="true" onBlur="saveToDatabase(this,'answer','<?php echo $faq[$k]["id"]; ?>')" onClick="showEdit(this);"><?php echo $faq[$k]["answer"]; ?></td> </tr> <?php } ?> </tbody> </table>
Call Update via jQuery AJAX
The following script receives the editable table cell reference, the column name and the column value edited inline. It prepares AJAX post request using these data and sends it to the server side via jQuery AJAX. In the PHP script, we update the database with this post data and send a response to AJAX call with the modified content.
<script> function saveToDatabase(editableObj,column,id) { $(editableObj).css("background","#FFF url(loaderIcon.gif) no-repeat right"); $.ajax({ url: "saveedit.php", type: "POST", data:'column='+column+'&editval='+editableObj.innerHTML+'&id='+id, success: function(data){ $(editableObj).css("background","#FDFDFD"); } }); } </script>
PHP MySQL Update
This PHP file is called via AJAX to execute MySQL update query for the edited content.
<?php require_once("dbcontroller.php"); $db_handle = new DBController(); $result = $db_handle->executeUpdate("UPDATE php_interview_questions set " . $_POST["column"] . " = '".$_POST["editval"]."' WHERE id=".$_POST["id"]); ?>
Komentar
Posting Komentar