Autosave data after specific time with jQuery and AJAX

On WordPress, you have noticed that while writing a blog post it will autosave the post as a draft after the specified interval.

In this tutorial, I am creating the similar type of functionality with jQuery and AJAX. Where I check for any value update in input element if it is then set an interval of 5 seconds.

Send an AJAX request to save data when the interval gets completed.

Autosave data after specific time with jQuery and AJAX


Contents

  1. Table structure
  2. Configuration
  3. HTML
  4. PHP
  5. Script
  6. Conclusion

 


 

1. Table structure

I am using posts table in the tutorial example.

CREATE TABLE `posts` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `title` varchar(100) NOT NULL,
  `content` text NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1;

 

2. Configuration

Create a config.php for database connection.

Completed Code

<?php
$host = "localhost"; /* Host name */
$user = "root"; /* User */
$password = ""; /* Password */
$dbname = "tutorial"; /* Database name */

$con = mysqli_connect($host, $user, $password,$dbname);
// Check connection
if (!$con) {
 die("Connection failed: " . mysqli_connect_error());
}

 

3. HTML

Create an input element to enter content and to store the post id create a hidden field set its default value to 0.

Completed Code

<input type='text' id='postTitle' placeholder='Enter post title'><br><br>
<textarea id='postContent' placeholder='Enter content'></textarea><br><br>
<input type='button' id='submit' value='Submit'>
<input type='hidden' id='postid' value='0' >

 

4. PHP

Create a new autosave.php file.

Check for the entry in the posts table if it does not exist then insert a new record and update the value of $postid with last insert id.

Otherwise, update the existing record and return $postid value as a response.

Completed Code

<?php
include "config.php";

$postid = $_POST['postid'];
$title = $_POST['title'];
$content = $_POST['content'];

// Check entry within table
$query = "SELECT COUNT(*) AS cntpost FROM posts WHERE id=".$postid;

$result = mysqli_query($con,$query);
$fetchdata = mysqli_fetch_array($result);
$count = $fetchdata['cntpost'];

if($count == 0){
 $insertquery = "INSERT INTO posts(title,content) values('".$title."','".$content."')";
 mysqli_query($con,$insertquery);
 $postid = mysqli_insert_id($con);
}else {
 $updatequery = "UPDATE posts SET title='" . $title . "',content='".$content."' where id=" . $postid;
 mysqli_query($con,$updatequery);
}

echo $postid;

 

5. Script

Define keyup event handler on postTitle and postContent ids. When it gets trigger then check if already a timeout defined or not. If defined then clear the interval and setTimout for 5 seconds (5000) and calls saveData() function.

In saveData() gets the input values and pass in the AJAX request as data. On successful callback update the <input type='hidden' id='postid'> value.

On the submit button click call saveData() function.

Completed Code

$(document).ready(function(){
 var timer;
 var timeout = 5000; // Timout duration
 $('#postTitle,#postContent').keyup(function(){
 
  if(timer) {
   clearTimeout(timer);
  }
  timer = setTimeout(saveData, timeout); 
 
 });
 
 $('#submit').click(function(){
  saveData();
 });
});

// Save data
function saveData(){
 
 var postid = $('#postid').val();
 var title = $('#postTitle').val().trim();
 var content = $('#postContent').val().trim();

 if(title != '' || content != ''){
  // AJAX request
  $.ajax({
   url: 'autosave.php',
   type: 'post',
   data: {postid:postid,title:title,content:content},
   success: function(response){
    $('#postid').val(response);
   } 
  });
 } 
}

 

6. Conclusion

If you want to autosave data after the regular interval without the need to check any change of content then you can use setInterval() method to send AJAX request on the specified interval.

Related Post

Spread the love

2 Comments

  1. Sohail said:

    THIS IS GREAT WORK.

    Will you please help me ..?
    ” I want a jquery/ajax code that should help me ,
    As I click in the checkbox, an ajax/jquery code should run to check that item in the database
    and popup a message of “Available” or “Not Available” ?
    Regards

    July 29, 2017
    Reply

Leave a Reply

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