Buku Tamu dengan Ajax


Sebelumnya saya udah pernah bikin buku tamu dengan menggunakan PHP standar. Kalo di bilang buku tamu nya jadul banget, ga interaktif, maksudnya adalah begitu tombol submit di tekan, dia akan nge-link. Tapi kali ini menggunakan ajax bgtu tombol submit ditekan maka otomatis tulisan komentar dari user akan langsung ter-load (dengan menggunakan sedikit manipulasi teknik Ajax) tanpa nge-link sama sekali, keren kan😀.

Memang sih Ajax cuma bikin pusing dan ngejelimet, (gw aja puyeng, :P) . Tapi kalo mau website yang interaktif mau tidak mau menggunakan teknik Ajax ini.

Langsung aja kita mulai

Jangan lupa bikin database nya dulu

Nama database nya ‘latihan‘, trus bikin tabel dengan nama ‘comments

CREATE TABLE IF NOT EXISTS `comments` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `name` varchar(100) NOT NULL,
 `comment` text NOT NULL,
 `date` datetime NOT NULL,
 PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=latin1 ;

1. Bikin file config.php

<?php
$hot    = 'localhost';
$user    = 'root';
$pass    = '';
$db_name= 'latihan';
$db        = new mysqli($host, $user, $pass, $db_name);
?>

2. Bikin file index.php

<?php
include_once 'config.php';
?>
<html>
<head>
<title>Komentar Ajax</title>
<script type="text/javascript" src="ajax.js">
</script>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div id="CommentList">
<!-- list start -->
<?php
$result = $db->query("SELECT id, name, comment, DATE_FORMAT(date, '%d/%m/%Y %H:%i:%s') AS local_date FROM comments");

while ($data = $result->fetch_object()){
?>
<div id="<?php echo $data->id;?>">
<div><a href="javascript:deleteContent(<?php echo $data->id;?>);">Remove</a></div>
<div><?php echo $data->name;?></div>
<div><?php echo $data->local_date;?></div>
<div><?php echo $data->comment;?></div>
</div>
<?php
}
?>
</div>
<br>
<div>Baru ada <span id="numComment"><?php echo $result->num_rows;?></span> komen.</div>
<div>
<div>
<strong>Komentar Donk </strong>
</div>
<div>
<form name="CommentForm" id="CommentForm" action="javascript:postContent()" method="post" />
<p><label for="name">Nama:</label> <input type="text" name="name" id="name" />
<p><label for="YourComment">Komentar:</label> <textarea name="YourComment" id="YourComment" /></textarea></p>
<p><input name="Submit" id="submit" type="submit" value="Submit" /></p>
</form>
</div>
</div>
<div id="alert"></div>
</body>
</html>

3. Bikin file ajax.js


/* create ajax XmlHttpRequest */

var xmlHttp = createXmlHttpRequest();
var obj = '';

function createXmlHttpRequest() {
 var xmlHttp = false;
 if (window.ActiveXObject) {
 xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
 } else {
 xmlHttp = new XMLHttpRequest();
 }
 if (!xmlHttp) {
 alert("Ops sorry We found some error!!");
 }
 return xmlHttp;
}

/* function for send data thrugh post method */

function postAjax(source, values, respons, hanres) {

 if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {

 obj = respons;

 xmlHttp.open("POST", source, true);

 xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
 xmlHttp.setRequestHeader("Content-length", values.length);
 xmlHttp.setRequestHeader("Connection", "close");
 xmlHttp.onreadystatechange = hanres;
 xmlHttp.send(values);
 } else {
 setTimeout('postAjax(source, values, respons, hanres)', 100000);
 }
}

/* functions for send and hendle respons for add new comment */

function postContent(){
 /* Query value that send to php.*/
 var commentValue = 'name=' + encodeURI( document.getElementById('name').value ) + '&YourComment=' + encodeURI( document.getElementById('YourComment').value );
 /*server side */
 var send_to = 'manage-comment.php';
 /*Div id for handle preloader image or errors.*/
 var respons = 'alert';
 postAjax(send_to, commentValue, respons, handleResponComment);
}

function handleResponComment(){
 if (xmlHttp.readyState == 4){
 if (xmlHttp.status == 200){
 /*I more prefer use json as response value from php*/
 var JSONRespons = eval('(' + xmlHttp.responseText + ')');
 if(JSONRespons.status == 1){
 /*
 * if inserting new commend succeed, then we call commentResponse function to show the new comment.
 */
 commentResponse(JSONRespons);
 }
 else{
 /*when new comment appeared, we have to re-enabel the form by calling enableForm() function using onload image event*/
 document.getElementById(obj).innerHTML = JSONRespons.message + '<img src="ajax-loading.gif" width="0" height="0" onload="enableForm();">';
 }
 } else {
 /*Incase we found errors on trancaction proccess.*/
 document.getElementById(obj).innerHTML = 'Error: ' + xmlHttp.statusText;
 }
 }
 else{
 /*
 * After submit new comment, we heve to diasable the form to prevent from re-submitng by user.
 * Also, show the preloader image, so user know his comment is being proceed.
 */
 document.getElementById(obj).innerHTML = '<img src="ajax-loading.gif">';
 document.getElementById('name').disabled=true;
 document.getElementById('YourComment').disabled=true;
 document.getElementById('submit').disabled=true;
 }
}

function commentResponse(JSONRespons){
 /*get listed comments*/
 var current_contents = document.getElementById('CommentList').innerHTML;
 /*Listed comments plus new comment that submited by user and inserted to database. */
 var newComment = current_contents + '<div id="' + JSONRespons.message_id + '"><div><a href="javascript:deleteContent(' + JSONRespons.message_id + ');">Remove</a></div><div><img src="ajax-loading.gif" width="0" height="0" onload="enableForm();">' + JSONRespons.name + '</div><div>' + JSONRespons.date + '</div><div>' + JSONRespons.comment + '</div></div>';
 /*get current total comment */
 var currTotalComm = document.getElementById('numComment').innerHTML;
 /*current comment plus one */
 document.getElementById('numComment').innerHTML = parseInt(currTotalComm) + parseInt(1);
 /*show up the new listed comments*/
 document.getElementById('CommentList').innerHTML = newComment;
 /*reset the form*/
 document.getElementById('CommentForm').reset();
 /*remove the preloader image*/
 document.getElementById('alert').innerHTML = '';
}

function enableForm(){
 /*re-enable the form after all process done. */
 document.getElementById('name').disabled=false;
 document.getElementById('YourComment').disabled=false;
 document.getElementById('submit').disabled=false;
}

/* functions for send and hendle respons for delete a comment */

function deleteContent(messageID){
 var postValue = 'id=' + messageID;
 var send_to = 'manage-comment.php';
 var respons = 'alert';

 input_box = window.confirm('Are you sure want to delete this comment?');
 if (input_box==true){
 postAjax(send_to, postValue, respons, handleDeletedComment);
 }
}

function handleDeletedComment(){
 if (xmlHttp.readyState == 4){
 if (xmlHttp.status == 200){
 var JSONRespons = eval('(' + xmlHttp.responseText + ')');
 if(JSONRespons.status == 1){
 deleteNow(JSONRespons.id);
 }
 else{
 document.getElementById(obj).innerHTML = JSONRespons.message;
 }
 } else {
 document.getElementById(obj).innerHTML = 'Error: ' + xmlHttp.statusText;
 }
 }
}

function deleteNow(id){
 var delete_comment = document.getElementById(id);
 var currTotalComm = document.getElementById('numComment').innerHTML;
 document.getElementById('numComment').innerHTML = parseInt(currTotalComm) - parseInt(1);
 delete_comment.parentNode.removeChild(delete_comment);
 enableForm();
 document.getElementById('alert').innerHTML = '';
}
 

4. Bikin file style.css

 body
{
 margin-left: 40px;
 margin-top: 10px;
 margin-right: 10px;
 margin-bottom: 0px;
 font-family:Arial, Helvetica, sans-serif;
 font-size:12px;
}

.Comment
{
 border-bottom:1px solid #CCC;
}
#CommentList
{
 width:350px;
}
.totalComment
{
 margin-top:10px;
}
.cssform p
{
 width: 300px;
 clear: left;
 margin: 0;
 padding: 5px 0 8px 0;
 padding-left: 50px;
}
.cssform label{
 font-weight: bold;
 float: left;
 margin-left: -50px;
 width: 80px;
}
.cssform input[type="text"]{
 width: 220px;
 border:1px solid #3686b8;
}
.cssform textarea
{
 width: 220px;
 height: 120px;
 border:1px solid #3686b8;
}
.cssform input[type="submit"]
{
 margin-left: 30px;
}
.SenderName
{
 font:bold 12px arial;
 padding: 3px;
}
.CommentDate
{
 padding: 3px;
}
.CommentContent
{
 padding: 3px;
}
.Remove
{
 float:right;
 padding: 3px;
}

.CommentForm
{
 width:350px;
 height:250px;
 border:solid 1px #CCC;
}

.HeaderForm
{
 border-bottom:solid 1px #CCC;
 background:url("lbl.png") repeat-x  scroll center transparent;
}

.CenterForm
{
 width:230px;
 margin-left:5px;
}
 

5. Bikin file manage-comment.php

 <?php
include_once 'config.php';

$today_date    = date("d/m/Y H:i:s");

function insert_comment($name, $comment){
 global $db;

 $sql_date    = date("Y-m-d H:i:s");
 $sql        = $db->query("INSERT INTO comments (name, comment, date) VALUES('$name', '$comment', '$sql_date')");

 if($sql){

 //get this comment id from db
 $result = $db->query("SELECT id FROM comments WHERE date = '$sql_date'");
 $data = $result->fetch_array(MYSQLI_ASSOC);
 $comment_id = $data['id'];
 return $comment_id;

 }
 else{

 return false;
 }
}

function delete_comment($id){
 global $db;

 $delete = $db->query("DELETE FROM comments WHERE id = '$id'");

 if($delete){

 return true;

 }
 else{

 return false;

 }
}

if(isset($_POST['name'])){

 $name = htmlentities($_POST['name']);
 $comment = htmlentities($_POST['YourComment']);
 $id = rand(000,999);

 if(empty($name)){

 $alert = array('status'=>'0', 'message'=>'Silahkan isi nama anda.');
 $alert = json_encode($alert);
 exit($alert);
 }

 if(empty($comment)){

 $alert = array('status'=>'0', 'message'=>'Silahkan isi komentar anda.');
 $alert = json_encode($alert);
 exit($alert);
 }

 $insert_comment = insert_comment($name, $comment);

 $alert = array('status'=>'1', 'date'=>$today_date, 'name'=>$name, 'comment'=>$comment, 'message_id'=>$insert_comment);
 $alert = json_encode($alert);
 exit($alert);
}

if(isset($_POST['id'])){

 $delete = delete_comment($_POST['id']);

 if($delete == true){

 $alert = array('status'=>'1','id'=>$_POST['id']);
 $alert = json_encode($alert);
 exit($alert);
 }
 else{

 $alert = array('status'=>'0', 'message'=>'Error deleting comment.');
 $alert = json_encode($alert);
 exit($alert);
 }
}
?>
 

Screen Shoot Output

sumber : ilmuwebsite, w3school

, , , , ,

  1. #1 by cool on 20 Juli, 2011 - 2:20 pm

    kk kok tlsnny Fatal error: Call to a member function query() on a non-object in C:\AppServ\www\coba\buku_tamu.php on line 15

  2. #2 by cool on 20 Juli, 2011 - 2:21 pm

    mksdny it d code ini g jln $result = $db->query(“SELECT id, name, comment, DATE_FORMAT(date, ‘%d/%m/%Y %H:%i:%s’) AS local_date FROM comments”);

  3. #3 by g on 17 April, 2012 - 11:45 am

    koq yg muncul di browser ini ya?
    Fatal error: Call to a member function fetch_object() on a non-object in C:\xampp\htdocs\latihan\query\eeq\index.php on line 17

    pada baris yg ini
    while ($data = $result->fetch_object()){

Tinggalkan Balasan

Isikan data di bawah atau klik salah satu ikon untuk log in:

Logo WordPress.com

You are commenting using your WordPress.com account. Logout / Ubah )

Gambar Twitter

You are commenting using your Twitter account. Logout / Ubah )

Foto Facebook

You are commenting using your Facebook account. Logout / Ubah )

Foto Google+

You are commenting using your Google+ account. Logout / Ubah )

Connecting to %s

%d blogger menyukai ini: