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 a similar type of functionality with jQuery and AJAX. Where I check for any value update in the 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
$stmt = $con->prepare("SELECT count(*) as cntpost FROM posts WHERE id=?");
$stmt->bind_param("i", $postid);
$stmt->execute();
$fetchdata = $stmt->get_result()->fetch_assoc();
$count = $fetchdata['cntpost'];

if($count == 0){

    $stmt = $con->prepare("INSERT INTO posts(title,content) VALUES (?, ?)");
    $stmt->bind_param("ss", $title, $content);
    $stmt->execute();
    $postid = $stmt->insert_id;
  
}else {
    $stmt = $con->prepare("UPDATE posts SET title=?,content=? where id=?");
    $stmt->bind_param("ssi", $title, $content,$postid); 
    $stmt->execute();
}

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.

If you found this tutorial helpful then don't forget to share.
Are you want to get implementation help, or modify or extend the functionality of this script? Submit paid service request.

7 thoughts on “Autosave data after specific time with jQuery and AJAX”

  1. 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

    Reply
  2. Super helpful post. Thank you for creating. One caveat is your example wide open to a SQL injection from a bad user:

    use something like the below with the bind_param to solve this:

    # Bind parameters. Types: s = string, i = integer, d = double, b = blob
    $stmt = $mysqli->prepare(“update posts set title=?,notes=? where num=?”);
    $stmt->bind_param(“ssi”,$title,$notes,$postid);
    $stmt->execute();

    Reply
  3. Thank you for your code, it will help me a lot in my project.
    I would like to get that after saving the values ​​in the database, the field will be blank.

    Reply

Leave a Comment