Membuat fitur autosave dengan ajax jquery

Posting Komentar

Kali ini lacodeid akan membahas cara autosave inputan dengan ajax jquery, bagi kalian yang sering menggunakan wordpress pasti sering post data lalu datanya tersimpan secara auto nah di tutorial kali ini saya akan memberikan caranya meggunakan bantuan javascripts, lansung saja tanpa basa basi kita menuju ke kodingya pertama buat file index.php dan save_auto.php.
buat nama database dilocalhost anda bebas untuk tabelnya disini saya berinama tbl_post seperti dibawah ini :
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`)  
 ) 
untuk jquernya silakan dikopas dibawah ini : 
<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>
lalu buat file 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"/> // baca id yang dikirim  
            <div id="autoSave"></div> //baca message data berhasil
          </div>  
    </div> 

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

</body>  
</html>
script dibawah ini yang nanti akan memproses autosave data kedalam database yang telah anda buat, cara kerjanya menggunakan setInterval mengatur waktu data dijalankan secara otomatis untuk dikirim ke file save_auto.php bila data sudah terpenuhi 
<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); //baca id inputan 
                            }  
                            $('#autoSave').text("Post save as draft");  
                            setInterval(function(){  
                              $('#autoSave').text('');  
                            }, 5000);  
                           }  
                      });  
                 }            
            }  
            setInterval(function(){   
             autoSave(); 
             }, 10000); //setting lama waktu yang akan dijalankan  
      }); 
    </script>
untuk file save_auto.php kodenya seperti dibawah ini :
<?php  
$connect = mysqli_connect("localhost", "root", "password", "name database");

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); 

  }

}  
sekian pembahasan autosave data kedalam database silakan dikopas koding diatas untuk pembelajaran, untuk tingkat lanjut silakan dikembangkan sendiri.

Related Posts

Posting Komentar