[adinserter block=”34″]Hello guys! today we are going to do a code that converts a DIV area to an editable HTML form and save the changes to the database.
We are going to use jQuery, PHP & MySQL ofcourse.
My inspiration for this post is Youtube!
For beginners, this post covers some useful stuff like:
Our database would look like this:
CREATE TABLE IF NOT EXISTS `users` ( `id` int(11) NOT NULL AUTO_INCREMENT, `firstname` varchar(32) NOT NULL, `lastname` varchar(32) NOT NULL, `gender` varchar(6) NOT NULL, `username` varchar(32) NOT NULL, `password` varchar(32) NOT NULL, `modified` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, PRIMARY KEY (`id`) ) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=56 ; – – Dumping data for table `users` – INSERT INTO `users` (`id`, `firstname`, `lastname`, `gender`, `username`, `password`, `modified`) VALUES (28, 'John', 'Dalisay', 'Male', 'john', 'john123′, '2012-07-23 13:26:39′);
our libs/db_connect.php code, change as you needed.
<?php $host = "localhost"; $db_name = "codeofaninja"; $username = "root"; $password = ""; try { $con = new PDO("mysql:host={$host};dbname={$db_name}", $username, $password); }catch(PDOException $exception){ //to handle connection error echo "Connection error: " . $exception->getMessage(); } ?>
our index.php code:
<html> <head> <title>Div to Form – https://codeofaninja.com/</title> <!–just to include some styles –> <link rel="stylesheet" type="text/css" href="css/style.css" /> </head> <body> <div id='banner'> <h2>Code of a Ninja Programming Blog</h2> <div>Converting a div to an editable HTML form and save changes to database</div> </div> <?php //just getting the id of the user to be edited $id = $_REQUEST['id']; //connect to database include 'libs/db_connect.php'; try { //prepare query $query = "select id, firstname, lastname, gender from users where id = ? limit 0,1″; $stmt = $con->prepare( $query ); //this is the first question mark on the query above $stmt->bindParam(1, $id); //execute our query $stmt->execute(); //store retrieved row to $row variable $row = $stmt->fetch(PDO::FETCH_ASSOC); //values to fill up our form $firstname = $row['firstname']; $lastname = $row['lastname']; $gender = $row['gender']; }catch(PDOException $exception){ //to handle error echo "Error: " . $exception->getMessage(); } ?> <!–start of our form –> <form id='user_form'> <!–id field is hidden, this is used to identify what row is to be edited–> <input type='hidden' value='<?php echo $id; ?>' name='id'/> <!– -just a form made with divs -when this div was clicked, it will be a form –> <div id='form_div'> <div class='field'> <div class='field_lbl'>Firstname:</div> <!–field name divs –> <div class='field_val'> <div class='field_div'> <!– -this shown on page load -and is hidden when the form_div was clicked -and will be shown again when the user clicked anywhere outside the form_div or cancel button –> <div id='firstname_text'><?php echo $firstname; ?></div> </div> <div class='field_input'> <!– -this is hidden on page load -and is shown when form_div was clicked -and will be hidden again when the user clicked anywhere outside the form_div or cancel button –> <input type='text' value='<?php echo $firstname; ?>' name='firstname' id='firstname'/> </div> <div class='clear_fix'></div> </div> <div class='clear_fix'></div> </div> <div class='clear_fix'></div> <!–same explanation above are given to these next fields–> <div class='field'> <div class='field_lbl'>Lastname:</div> <div class='field_val'> <div class='field_div'> <div id='lastname_text'><?php echo $lastname; ?></div> </div> <div class='field_input'><input type='text' value='<?php echo $lastname; ?>' name='lastname' id='lastname' /></div> <div class='clear_fix'></div> </div> <div class='clear_fix'></div> </div> <div class='clear_fix'></div> <div class='field'> <div class='field_lbl'>Gender:</div> <div class='field_val'> <div class='field_div'> <div id='gender_text'><?php echo $gender; ?></div> </div> <div class='field_input'> <select name='gender' id='gender'> <option <?php if($gender == "Male") echo "selected"; ?> >Male</option> <option <?php if($gender == "Female") echo "selected"; ?>>Female</option> </select> </div> <div class='clear_fix'></div> </div> <div class='clear_fix'></div> </div> <div class='clear_fix'></div> <!– -these buttons are hidden on page load -they are shown when form_div was clicked -and will be hidden again when the user clicked anywhere outside the form_div or cancel button —> <div class='btns'> <input type='button' value='Save' id='save_btn' /> <input type='button' value='Cancel' id='cancel_btn' /> </div> </div> </form> <script src="js/jquery.min.js "></script> <script type='text/javascript'> $( document ).ready( function(){ enable_hover(); //hover effect is enabled on page load $('#form_div').click(function(){ edit_mode(); }); //when clicked the cancel button $('body').on('click', '#cancel_btn', function(){ normal_mode(); //back to normal mode }); //we used the jquery delegate func for live events $('body').on('click', '#save_btn', function(){ //save first here //get the current values var fn = $('#firstname').val(); var ln = $('#lastname').val(); var gender = $('#gender').val(); //the make it appear in the UI $('#firstname_text').text(fn); $('#lastname_text').text(ln); $('#gender_text').text(gender); //save the actual data //we use jquery serialize to serialize the form and easily get the form values //this is how to submit or post form without page refresh $.post("save.php", $("#user_form").serialize(), function(data) { //you can do any event you want here alert(data); //alert that the date were saved normal_mode(); //back to normal mode }); }); //this way we can detect if the user clicked outside the form_div area $("body").click(function(e) { if (e.target.id == "form_div" || $(e.target).parents("#form_div").size()) { //if clicked inside form_div area, //do nothing } else { //if the user clicked outside the form_div area, //we'll be in normal mode normal_mode(); } }); }); function edit_mode(){ $('#form_div').css({ 'background-color' : '#fff' }); //just make a white background $('#form_div').unbind('hover'); //disable hover $('.field_div').hide(); //hide the text $('.field_input').show(); //show the form element $('.btns').show(); //show the buttons } //the normal state is the appearance of the page/element when it was first loaded function normal_mode(){ enable_hover(); //enable the hover effect again $('.field_div').show(); //show the texts $('.field_input').hide(); //hide the input elements $('.btns').hide(); //hide the buttons } //hover effect is used when NOT in 'edit form' mode //we unbind this effect when we are in the 'edit form' mode function enable_hover(){ $('#form_div').hover( function(){ //when we hover form_div, bg will be gray with a bit of rounded corners $(this).css({ 'background-color' : '#dcdcdc', '-moz-border-radius' : '5px', 'border-radius' : '5px' }); }, function(){ //when mouse is not hovered, bg will be transparent $(this).css({'background-color' : 'transparent'}); } ); } </script> </body> </html>
our save.php code:
<?php //this is where the data were updated/saved //connect to database include 'libs/db_connect.php'; try{ //write query //in this case, it seemed like we have so many fields to pass and //its kinda better if we'll label them and not use question marks //like what we used here $query = "update users set firstname = :firstname, lastname = :lastname, gender = :gender where id = :id"; //prepare query for excecution $stmt = $con->prepare($query); //bind the parameters $stmt->bindParam(':firstname', $_POST['firstname']); $stmt->bindParam(':lastname', $_POST['lastname']); $stmt->bindParam(':gender', $_POST['gender']); $stmt->bindParam(':id', $_POST['id']); // Execute the query if( $stmt->execute() ){ echo "Record was updated."; }else{ echo "Unable to update record."; } }catch(PDOException $exception){ //to handle error echo "Error: " . $exception->getMessage(); } ?>
our style.css file:
body{ margin:0; font-family:arial, verdana, tahoma; } #banner{ margin:0 0 50px 0; padding:20px; width:100%; height:100px; } #form_div{ padding:10px; width:500px; margin:0 auto; } .field{ padding: 10px; } .field_lbl{ float:left; margin:0 10px 0 0; width:80px; font-weight:bold; } .field_val{ float:left; } .field_div{ display:block; } .field_input{ display:none; } .btns{ display:none; margin:0 0 0 8px; } .clear_fix{ clear:both; }
Thank you guys for your kind comments, messages and suggestions. I really appreciate it!
You can download all the code used in this tutorial for only $9.99 $5.55!
[purchase_link id=”12303″ text=”Download Now” style=”button” color=”green”]
[adinserter block=”1″]
Thank you for learning from our post about Convert a DIV Area to an Editable HTML Form.