Data Autosave System using PHP, MySQL and AJAX

Data Autosave System using PHP, MySQL and AJAX

Imagine you are going to publish an article or post on your website and you are halfway through and suddenly your Internet connection goes down or your PC shuts off or any kind of hardware/software issue occurs on your system, all your hard work goes in vain and you have to again start from scratch to prevent such kind of accidents many famous CMS like WordPress, Drupal etc. offers you the feature of Autosaving, the autosaving feature is simple to understand it automatically saves and back up your data at regular interval of time so that even if some kind of problem occurs in your system you will be able to recover your last autosaved work.
In this tutorial, we are going to create such a system which will automatically save your created post at regular interval of time.

Prerequisites

  • Good understanding of PHP and MySQL
  • Good Understanding of AJAX and Javascript

Project Hierarchy

Project Hierarchy Autosave using PHP, MySQL and AJAX
  •  AJAX.js – The file contains the code which will send the request to the server at regular intervals of time using an asynchronous approach.
  •  Autosave.php – The script contains the code which will run on the server and is responsible to insert and update the date in the database.
  •  Index.php – This file will show the homepage of the application and the UI.
  •  Style.css – The stylesheet will provide some style to the HTML form.

Working

Initial Stage: Initially the data first needs to be inserted into the database and then needs to be updated. So, at first, the data is inserted into the database when the primary request is made to the server and primary key is retrieved as a response from the server.
Secondary Stage: As the primary key of the record is retrieved in the initial stage from the database, now we can update the specific record from the database by sending asynchronous requests to the server at a regular interval of time.
Working of autosave system

Autosave content using PHP, MySQL and AJAX

Now let’s get ready to write some code first we will create the database to store our data, to create a database execute the following query in your MySQL console.
CREATE DATABASE autosave;
Markup
We have successfully created our database, now we will create a table called “post” into it, type in the following query in your MySQL console.
create table autosave(
id int PRIMARY KEY AUTO_INCREMENT,
title char(225),
content TEXT);
Markup
Now Open up your favourite text editor and create a new file called “index.php” and type the following code into it.
<!DOCTYPE html>
<html>
<head>
<title>AutoSave Post using PHP MySQL and AJAX</title>
<link type="text/css" rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<h1>Create a new post</h1>
<form>
<input type="text" name="title" placeholder="Enter post title" required><br /><br />
<textarea placeholder="Enter content" name="content" required></textarea><br /><br />
<input type="hidden" name="id" />
</form>
<div id='message'></div>
</div>
<script type="text/javascript" src="ajax.js"></script>
</body></html>
Markup
If you notice we have added a hidden input field in the above HTML form which will hold the id (primary key) of the inserted record. We will discuss it about later in this tutorial and we will also see how it will work and play the key role.
Let’s apply some styling to our boring and ugly HTML form. Create a new file called “style.css” in the root directory and type in the following code into it.
body{
padding : 0;
margin: 0;
}
h1{
font-family: sans-serif;
font-weight: normal;
}
.container{
width:100%;
max-width: 800px;
margin: auto;
padding: 20px;
}
input[type="text"]{
width: 100%;
border: none;
outline: none;
border:1px solid lightgrey;
border-radius: 5px;
padding:10px;
box-sizing: border-box;
}
textarea{
width: 100%;
box-sizing: border-box;
height:200px;
border:1px solid lightgrey;
border-radius: 5px;
padding: 10px;
}
CSS
We have created our form but we don’t have a script to save its content so let's write the PHP script to perform the database modifications, create a new file called “autosave.php” and write the following code into it.
date_default_timezone_set('Asia/Kolkata'); //you can add your own timezone
$host = 'localhost';
$user = 'your_db_username';
$pass = 'your_db_password';
$db = 'autosave';
$conn = new mysqli($host, $user, $pass, $db);
function insertPost($title,$content, $conn){
$sql = "INSERT INTO post VALUES(null, ?, ?)";
$stmt = $conn->stmt_init();
if($stmt->prepare($sql)){
$stmt->bind_param('ss',$title,$content);
if($stmt->execute()){
echo $conn->insert_id;
}
}}
function updatePost($title,$content,$id, $conn){
$sql = "UPDATE post SET title = ?, content = ? WHERE id = ?";
$stmt = $conn->stmt_init();
if($stmt->prepare($sql)){
$stmt->bind_param('ssi',$title,$content,$id);
if($stmt->execute()){
echo "<i>Draft Saved at ".date("h:i:s a")."</i>";
}
}}
if(isset($_GET['save'])){
$title = $_POST['title'];
$content = $_POST['content'];
$id = $_POST['id'];
if($id != ''){
updatePost($title, $content,$id, $conn);
}
else{
insertPost($title, $content, $conn);
}}
?>
PHP
In the above script, we created two functions insertPost() and updatePost(), the insertPost() function will simply insert the record into the database and will be called only once when the $id (the hidden input field value) will be empty the function will return the inserted record primary key.
The updatePost() function will update the post by using the primary key which was returned by the insertPost() function previously.
Now we will write the AJAX code which is the core of this system, create a new file called “ajax.js” and type in the following code into it.
function getData(){
var fd = new FormData();
var title = document.getElementsByName('title')[0].value;
var content = document.getElementsByName('content')[0].value;
var id = document.getElementsByName('id')[0].value;
fd.append('title',title);
fd.append('content',content);
fd.append('id',id);
return fd;
}
function savePost(){
try{
var xhttp = new XMLHttpRequest();
}
catch(e){
console.log(e);
}
var data = getData();
xhttp.open('POST','autosave.php?save=true');
xhttp.send(data);
xhttp.onreadystatechange = function(){
if(this.status == 200 && this.readyState == 4){
if(data.get('id') == ""){
document.getElementsByName('id')[0].value = this.responseText;
}
else{
document.getElementById('message').innerHTML = this.responseText;
}
console.log(this.responseText);
}
}
}
setInterval(savePost,10000); //savePost will be called in every 10 seconds
JavaScript
In the above script, we defined two functions getData() and savePost(). The getData() function will retrieve the data from the HTML form and return it.
The savePost() function will send asynchronous requests to autotsave.php, the function has two conditions first when the value of the hidden field is undefined or null in that case the insertPost() function will be called from the server side, in this case, the value of the primary key is retrieved from the server and assigned to the hidden input field.
In the else condition, the request is sent to the autosave.php and updatePost() function is called and the primary key is passed which was retrieved previously when the initial request was made.
In the end, we are calling the javascript setInteraval() method which will call the savePost() function every 10 seconds.
Congratulations, we have successfully created our autosave system.

Comments