Tuesday 15 March 2016

Auto Save Data using Ajax, Jquery, PHP and Mysql


In this post we are going to learn how to save data automatically in database on specific time interval using Ajax Jquery with PHP and Mysql. This type of functionality you have seen into Wordpress Admin side if you have used Wordpress. If you have used Wordpress CMS, then at Admin side when we have create new post or page then after a specific interval of time it will save as draft our post or page automatically in Database. So our data will safe if we are forget to publish our content and we come after some time then our content will be placed in Database as draft. So, Tthis type of functionality we are going to learn into this post. In this post We will describe you a simple post example. In We have simple form for posting simple article with title and description. When user enter title and description thenafter some time interval post automatically insert into database table. This things happends only after user enter post title and description. In this tutorial if post enter for first time then it insert into database table but if post already inserted then it will update that post data on regular time interval.

Source Code


index.php


 
 <html>  
      <head>  
           <meta name="viewport" content="initial-scale=1.0, user-scalable=no">  
           <meta charset="utf-8">  
           <title>Webslesson Tutorial</title>  
           <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
     <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>  
      </head>  
      <body>  
           <div class="container">  
                <br />  
                <h2 align="center">Auto Save Data using Ajax, Jquery, PHP and Mysql</h2>  
                <br />  
                <div class="form-group">  
                     <label>Enter Post Title</label>  
                     <input type="text" name="post_title" id="post_title" class="form-control" />  
                </div>  
                <div class="form-group">  
                     <label>Enter Post Description</label>  
                     <textarea name="post_description" id="post_description" rows="6" class="form-control"></textarea>  
                </div>
    <div class="form-group">
     <button type="button" name="publish" class="btn btn-info">Publish</button>
    </div>
                <div class="form-group">  
                     <input type="hidden" name="post_id" id="post_id" />  
                     <div id="autoSave"></div>  
                </div>  
           </div>  
      </body>  
 </html>  
 <script>  
 $(document).ready(function(){  
      function autoSave()  
      {  
           var post_title = $('#post_title').val();  
           var post_description = $('#post_description').val();  
           var post_id = $('#post_id').val();  
           if(post_title != '' && post_description != '')  
           {  
                $.ajax({  
                     url:"save_post.php",  
                     method:"POST",  
                     data:{postTitle:post_title, postDescription:post_description, postId:post_id},  
                     dataType:"text",  
                     success:function(data)  
                     {  
                          if(data != '')  
                          {  
                               $('#post_id').val(data);  
                          }  
                          $('#autoSave').text("Post save as draft");  
                          setInterval(function(){  
                               $('#autoSave').text('');  
                          }, 5000);  
                     }  
                });  
           }            
      }  
      setInterval(function(){   
           autoSave();   
           }, 10000);  
 });  
 </script>
 

save_post.php


 
 <?php  
 $connect = mysqli_connect("localhost", "root", "", "testing");
 if(isset($_POST["postTitle"]) && isset($_POST["postDescription"]))
 {
  $post_title = mysqli_real_escape_string($connect, $_POST["postTitle"]);
  $post_description = mysqli_real_escape_string($connect, $_POST["postDescription"]);
  if($_POST["postId"] != '')  
  {  
    //update post  
    $sql = "UPDATE tbl_post SET post_title = '".$post_title."', post_description = '".$post_description."' WHERE post_id = '".$_POST["postId"]."'";  
    mysqli_query($connect, $sql);  
  }  
  else  
  {  
    //insert post  
    $sql = "INSERT INTO tbl_post(post_title, post_description, post_status) VALUES ('".$post_title."', '".$post_description."', 'draft')";  
    mysqli_query($connect, $sql);  
    echo mysqli_insert_id($connect);  
  }
 }  
 ?>
 

Database

 
 CREATE TABLE IF NOT EXISTS `tbl_post` (  
  `post_id` int(11) NOT NULL AUTO_INCREMENT,  
  `post_title` text NOT NULL,  
  `post_description` text NOT NULL,  
  `post_status` varchar(15) NOT NULL,  
  PRIMARY KEY (`post_id`)  
 ) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;
 

18 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Thank you for sharing; it’s nice and helpful information. I hope I could read more information like this in the next visit.
    regards,
    SEO melbourne

    ReplyDelete
  3. Wheres the link for script.js, bootstrap.js i get 404 error

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
  4. $('#autoSave').text("Post save as draft");
    setInterval(function(){
    $('#autoSave').text('');
    }, 5000);

    You can place these lines in the conditional statement that check if data is not empty in case the response is failed for some reason. Otherwise, it will simply display "Post saved as draft" even in case of failure. So, it's better having them placed in conditional statements.

    ReplyDelete
  5. $('#autoSave').text("Post save as draft");
    setInterval(function(){
    $('#autoSave').text('');
    }, 5000);

    You can place these lines in the conditional statement that check if data is not empty in case the response is failed for some reason. Otherwise, it will simply display "Post saved as draft" even in case of failure. So, it's better having them placed in conditional statements.

    ReplyDelete
  6. The auto save function saves one time olny

    ReplyDelete
  7. No input sanitation for SQL injection?

    ReplyDelete
  8. Getting HTTP 404 error. Looks like ajax can not find the php file. Index.php and save_post.php has to be in the same theme folder?

    Thanks

    ReplyDelete
  9. post id will be empty in other requests

    ReplyDelete
  10. $postid = mysqli_insert_id($connect);
    should be outside the bracket
    echo $postid;

    ReplyDelete
  11. Thanks you!
    Is it possible to get the field completely blank after a few seconds?

    ReplyDelete
  12. Works perfectly. But I wish there was a CRUD version of this. Create, Read, Update, Delete.

    ReplyDelete