PHP MySQL jQuery Ajax HTML Editable Content

php-inline-edit

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"]);
?>

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *

Show Buttons
Hide Buttons
Social Media Auto Publish Powered By : XYZScripts.com