article

Thursday, April 8, 2021

PHP Mysqli Autosave data after specific time with jQuery AJAX

PHP Mysqli Autosave data after specific time with jQuery AJAX

--
-- Table structure for table `post`
--

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

--
-- Dumping data for table `post`
--

INSERT INTO `post` (`id`, `title`, `content`) VALUES
(1, 'dfsdf', 'sdf'),
(2, 'sfdf', 'sdasdasd'),
(3, 'PHP Mysqli Autosave data after specific time with jQuery AJAX', 'PHP Mysqli Autosave data after specific time with jQuery AJAX');

--
-- Indexes for dumped tables
--

--
-- Indexes for table `post`
--
ALTER TABLE `post`
  ADD PRIMARY KEY (`id`);

--
-- AUTO_INCREMENT for dumped tables
--

--
-- AUTO_INCREMENT for table `post`
--
ALTER TABLE `post`
  MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=1;

The setTimeout() method calls a function or evaluates an expression after a specified number of milliseconds.

1000 ms = 1 second.

In this tutorial set an interval of 5 seconds 

//index.php
<html>
<head>
<title>PHP Mysqli Autosave data after specific time with jQuery AJAX</title>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />		
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
<p><h1 align="center">PHP Mysqli Autosave data after specific time with jQuery AJAX</h1></p>
<div class="container">
<div class="row">
	<b>Title :</b> <input type='text' id='postTitle' class="form-control" placeholder='Enter post title'><br><br>
	<b>Content :</b> <textarea id='postContent' class="form-control" placeholder='Enter content' rows="5"></textarea><br><br>
	<input type='button' class="btn btn-default" id='submit' value='Submit'>
	<input type='hidden' id='postid' value='0' >
</div>
</div>
<script>
//setTimeout(function(){ alert("Hello"); }, 3000); //Display an alert box after 3 seconds (3000 milliseconds):
$(document).ready(function(){
 var timer;
 var timeout = 5000; // Timout duration 1000 ms = 1 second.
 $('#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); 
	alert('Save Success');
   } 
  });
 } 
}
</script>
</body>
</html>
autosave.php
//autosave.php
<?php
include "dbcon.php";

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

$stmt = $conn->prepare("SELECT count(*) as cntpost FROM post WHERE id=?");
$stmt->bind_param("i", $postid);
$stmt->execute();
$fetchdata = $stmt->get_result()->fetch_assoc();
$count = $fetchdata['cntpost'];

if($count == 0){

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

echo $postid;
dbcon.php
//dbcon.php
<?php
$conn = new mysqli('localhost','root','','testingdb');
if ($conn->connect_error) {
    die('Error : ('. $conn->connect_errno .') '. $conn->connect_error);
}
?>

Related Post