Ok, I wanted to share a trick I came up with yesterday working on a project. What I needed was to create a table from a MySQL result, and be able to edit all the fields in the table. I decided to use JQUERY and AJAX to accomplish this.
I decided on JQUERY and AJAX for a few reasons. I didn’t want the user to have to leave or reload the page each time a value was changed. And, speed was important too and I find AJAX is a great way to boost your load times as most of the work is done in the background.
So what does it do? Well it creates a text element that changes to an HTML input on click. After the value is changed it is sent via AJAX to another page that inserts the new data into MySQL.
What you need, You will need the following JavaScript files (Note: You only need jquery.js if you are not currently using any JQUERY on your page.)
- http://shopbluesoft.com/design/code_deposit/edit.js
- http://shopbluesoft.com/design/code_deposit/jquery.editinplace.packed.js
- http://shopbluesoft.com/design/code_deposit/jquery.js
Once you download these call them in the HEAD section of your page.
<head>
<script type=”text/javascript” src=”../js/jquery.editinplace.packed.js”></script>
<script type=”text/javascript” src=”../js/edit.js”></script>
<script type=”text/javascript” src=”../js/jquery.js”></script></head>
After this all you need to do is give an element the name “editme1″ like so
<span class=”editme1″ id=”links-title-1′”>This can be changed</span>
Now what I have done is set it up in PHP to separate the id by “-” and get the table name from the first value, the column from the second and the row id in the third like so
id=”table-column-id”
This allows you to reuse this script anywhere and simply change the ID to allow it update any MySQL field.
Here is the php that handles the request. (edit_in_place_server.php)
<?
include(‘../connect.inc’);$update_value = $_POST['update_value'];
$element_id = $_POST['element_id'];
$original = $_POST['original_html'];$element = explode(“-”, $element_id);
$table = $element['0'];
$col = $element['1'];
$row_id = $element['2'];$sql = “UPDATE “.$table.” SET “.$col.”=’”.$update_value.”‘ WHERE id=’”.$row_id.”‘”;
$result = mysql_query($sql) or die(mysql_error());if($result){ echo $update_value; }
The script echos the new value and it is returned to the page to replace the old value.
Feel free to use this code anywhere you can, I hope it helps.
