Back To Top

Loading...

Apa pendapat anda dengan BLOG ini ?

Senin, 11 April 2011

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 :D .
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
Source code   
1
2
3
4
56
7
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
Source code   
  1. <?php
  2. $hot = 'localhost';
  3. $user = 'root';
  4. $pass = '';
  5. $db_name= 'latihan';
  6. $db = new mysqli($host, $user, $pass, $db_name);
  7. ?>

2. Bikin file index.php
Source code   
  1. <?php
  2. include_once 'config.php';
  3. ?>
  4. <html>
  5. <head>
  6. <title>Komentar Ajax</title>
  7. <script type="text/javascript" src="ajax.js">
  8. </script>
  9. <link rel="stylesheet" href="style.css" />
  10. </head>
  11. <body>
  12. <div id="CommentList">
  13. <!-- list start -->
  14. <?php
  15. $result = $db->query("SELECT id, name, comment, DATE_FORMAT(date, '%d/%m/%Y %H:%i:%s') AS local_date FROM comments");
  16.  
  17. while ($data = $result->fetch_object()){
  18. ?>
  19. <div id="<?php echo $data->id;?>">
  20. <div><a href="javascript:deleteContent(<?php echo $data->id;?>);">Remove</a></div>
  21. <div><?php echo $data->name;?></div>
  22. <div><?php echo $data->local_date;?></div>
  23. <div><?php echo $data->comment;?></div>
  24. </div>
  25. <?php
  26. }
  27. ?>
  28. </div>
  29. <br>
  30. <div>Baru ada <span id="numComment"><?php echo $result->num_rows;?></span> komen.</div>
  31. <div>
  32. <div>
  33. <strong>Komentar Donk </strong>
  34. </div>
  35. <div>
  36. <form name="CommentForm" id="CommentForm" action="javascript:postContent()" method="post" />
  37. <p><label for="name">Nama:</label> <input type="text" name="name" id="name" />
  38. <p><label for="YourComment">Komentar:</label> <textarea name="YourComment" id="YourComment" /></textarea></p>
  39. <p><input name="Submit" id="submit" type="submit" value="Submit" /></p>
  40. </form>
  41. </div>
  42. </div>
  43. <div id="alert"></div>
  44. </body>
  45. </html>
3. Bikin file ajax.js
Source code   
  1. /* create ajax XmlHttpRequest */
  2.  
  3. var xmlHttp = createXmlHttpRequest();
  4. var obj = '';
  5.  
  6. function createXmlHttpRequest() {
  7. var xmlHttp = false;
  8. if (window.ActiveXObject) {
  9. xmlHttp = new ActiveXObject(&quot;Microsoft.XMLHTTP&quot;);
  10. } else {
  11. xmlHttp = new XMLHttpRequest();
  12. }
  13. if (!xmlHttp) {
  14. alert(&quot;Ops sorry We found some error!!&quot;);
  15. }
  16. return xmlHttp;
  17. }
  18.  
  19. /* function for send data thrugh post method */
  20.  
  21. function postAjax(source, values, respons, hanres) {
  22.  
  23. if (xmlHttp.readyState == 4 || xmlHttp.readyState == 0) {
  24.  
  25. obj = respons;
  26.  
  27. xmlHttp.open(&quot;POST&quot;, source, true);
  28.  
  29. xmlHttp.setRequestHeader(&quot;Content-type&quot;, &quot;application/x-www-form-urlencoded&quot;);
  30. xmlHttp.setRequestHeader(&quot;Content-length&quot;, values.length);
  31. xmlHttp.setRequestHeader(&quot;Connection&quot;, &quot;close&quot;);
  32. xmlHttp.onreadystatechange = hanres;
  33. xmlHttp.send(values);
  34. } else {
  35. setTimeout('postAjax(source, values, respons, hanres)', 100000);
  36. }
  37. }
  38.  
  39. /* functions for send and hendle respons for add new comment */
  40.  
  41. function postContent(){
  42. /* Query value that send to php.*/
  43. var commentValue = 'name=' + encodeURI( document.getElementById('name').value ) + '&amp;YourComment=' + encodeURI( document.getElementById('YourComment').value );
  44. /*server side */
  45. var send_to = 'manage-comment.php';
  46. /*Div id for handle preloader image or errors.*/
  47. var respons = 'alert';
  48. postAjax(send_to, commentValue, respons, handleResponComment);
  49. }
  50.  
  51. function handleResponComment(){
  52. if (xmlHttp.readyState == 4){
  53. if (xmlHttp.status == 200){
  54. /*I more prefer use json as response value from php*/
  55. var JSONRespons = eval('(' + xmlHttp.responseText + ')');
  56. if(JSONRespons.status == 1){
  57. /*
  58. * if inserting new commend succeed, then we call commentResponse function to show the new comment.
  59. */
  60. commentResponse(JSONRespons);
  61. }
  62. else{
  63. /*when new comment appeared, we have to re-enabel the form by calling enableForm() function using onload image event*/
  64. document.getElementById(obj).innerHTML = JSONRespons.message + '&lt;img src=&quot;ajax-loading.gif&quot; width=&quot;0&quot; height=&quot;0&quot; onload=&quot;enableForm();&quot;&gt;';
  65. }
  66. } else {
  67. /*Incase we found errors on trancaction proccess.*/
  68. document.getElementById(obj).innerHTML = 'Error: ' + xmlHttp.statusText;
  69. }
  70. }
  71. else{
  72. /*
  73. * After submit new comment, we heve to diasable the form to prevent from re-submitng by user.
  74. * Also, show the preloader image, so user know his comment is being proceed.
  75. */
  76. document.getElementById(obj).innerHTML = '&lt;img src=&quot;ajax-loading.gif&quot;&gt;';
  77. document.getElementById('name').disabled=true;
  78. document.getElementById('YourComment').disabled=true;
  79. document.getElementById('submit').disabled=true;
  80. }
  81. }
  82.  
  83. function commentResponse(JSONRespons){
  84. /*get listed comments*/
  85. var current_contents = document.getElementById('CommentList').innerHTML;
  86. /*Listed comments plus new comment that submited by user and inserted to database. */
  87. var newComment = current_contents + '&lt;div id=&quot;' + JSONRespons.message_id + '&quot;&gt;&lt;div&gt;&lt;a href=&quot;javascript:deleteContent(' + JSONRespons.message_id + ');&quot;&gt;Remove&lt;/a&gt;&lt;/div&gt;&lt;div&gt;&lt;img src=&quot;ajax-loading.gif&quot; width=&quot;0&quot; height=&quot;0&quot; onload=&quot;enableForm();&quot;&gt;' + JSONRespons.name + '&lt;/div&gt;&lt;div&gt;' + JSONRespons.date + '&lt;/div&gt;&lt;div&gt;' + JSONRespons.comment + '&lt;/div&gt;&lt;/div&gt;';
  88. /*get current total comment */
  89. var currTotalComm = document.getElementById('numComment').innerHTML;
  90. /*current comment plus one */
  91. document.getElementById('numComment').innerHTML = parseInt(currTotalComm) + parseInt(1);
  92. /*show up the new listed comments*/
  93. document.getElementById('CommentList').innerHTML = newComment;
  94. /*reset the form*/
  95. document.getElementById('CommentForm').reset();
  96. /*remove the preloader image*/
  97. document.getElementById('alert').innerHTML = '';
  98. }
  99.  
  100. function enableForm(){
  101. /*re-enable the form after all process done. */
  102. document.getElementById('name').disabled=false;
  103. document.getElementById('YourComment').disabled=false;
  104. document.getElementById('submit').disabled=false;
  105. }
  106.  
  107. /* functions for send and hendle respons for delete a comment */
  108.  
  109. function deleteContent(messageID){
  110. var postValue = 'id=' + messageID;
  111. var send_to = 'manage-comment.php';
  112. var respons = 'alert';
  113.  
  114. input_box = window.confirm('Are you sure want to delete this comment?');
  115. if (input_box==true){
  116. postAjax(send_to, postValue, respons, handleDeletedComment);
  117. }
  118. }
  119.  
  120. function handleDeletedComment(){
  121. if (xmlHttp.readyState == 4){
  122. if (xmlHttp.status == 200){
  123. var JSONRespons = eval('(' + xmlHttp.responseText + ')');
  124. if(JSONRespons.status == 1){
  125. deleteNow(JSONRespons.id);
  126. }
  127. else{
  128. document.getElementById(obj).innerHTML = JSONRespons.message;
  129. }
  130. } else {
  131. document.getElementById(obj).innerHTML = 'Error: ' + xmlHttp.statusText;
  132. }
  133. }
  134. }
  135.  
  136. function deleteNow(id){
  137. var delete_comment = document.getElementById(id);
  138. var currTotalComm = document.getElementById('numComment').innerHTML;
  139. document.getElementById('numComment').innerHTML = parseInt(currTotalComm) - parseInt(1);
  140. delete_comment.parentNode.removeChild(delete_comment);
  141. enableForm();
  142. document.getElementById('alert').innerHTML = '';
  143. }
4. Bikin file style.css
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=&quot;text&quot;]{
width: 220px;
border:1px solid #3686b8;
}
.cssform textarea
{
width: 220px;
height: 120px;
border:1px solid #3686b8;
}
.cssform input[type=&quot;submit&quot;]
{
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(&quot;lbl.png&quot;) repeat-x  scroll center transparent;
}
 
.CenterForm
{
width:230px;
margin-left:5px;
}
5. Bikin file manage-comment.php
Source code   
  1. <?php
  2. include_once 'config.php';
  3.  
  4. $today_date = date("d/m/Y H:i:s");
  5.  
  6. function insert_comment($name, $comment){
  7. global $db;
  8.  
  9. $sql_date = date("Y-m-d H:i:s");
  10. $sql = $db->query("INSERT INTO comments (name, comment, date) VALUES('$name', '$comment', '$sql_date')");
  11.  
  12. if($sql){
  13.  
  14. //get this comment id from db
  15. $result = $db->query("SELECT id FROM comments WHERE date = '$sql_date'");
  16. $data = $result->fetch_array(MYSQLI_ASSOC);
  17. $comment_id = $data['id'];
  18. return $comment_id;
  19.  
  20. }
  21. else{
  22.  
  23. return false;
  24. }
  25. }
  26.  
  27. function delete_comment($id){
  28. global $db;
  29.  
  30. $delete = $db->query("DELETE FROM comments WHERE id = '$id'");
  31.  
  32. if($delete){
  33.  
  34. return true;
  35.  
  36. }
  37. else{
  38.  
  39. return false;
  40.  
  41. }
  42. }
  43.  
  44. if(isset($_POST['name'])){
  45.  
  46. $name = htmlentities($_POST['name']);
  47. $comment = htmlentities($_POST['YourComment']);
  48. $id = rand(000,999);
  49.  
  50. if(empty($name)){
  51.  
  52. $alert = array('status'=>'0', 'message'=>'Silahkan isi nama anda.');
  53. $alert = json_encode($alert);
  54. exit($alert);
  55. }
  56.  
  57. if(empty($comment)){
  58.  
  59. $alert = array('status'=>'0', 'message'=>'Silahkan isi komentar anda.');
  60. $alert = json_encode($alert);
  61. exit($alert);
  62. }
  63.  
  64. $insert_comment = insert_comment($name, $comment);
  65.  
  66. $alert = array('status'=>'1', 'date'=>$today_date, 'name'=>$name, 'comment'=>$comment, 'message_id'=>$insert_comment);
  67. $alert = json_encode($alert);
  68. exit($alert);
  69. }
  70.  
  71. if(isset($_POST['id'])){
  72.  
  73. $delete = delete_comment($_POST['id']);
  74.  
  75. if($delete == true){
  76.  
  77. $alert = array('status'=>'1','id'=>$_POST['id']);
  78. $alert = json_encode($alert);
  79. exit($alert);
  80. }
  81. else{
  82.  
  83. $alert = array('status'=>'0', 'message'=>'Error deleting comment.');
  84. $alert = json_encode($alert);
  85. exit($alert);
  86. }
  87. }
  88. ?>
Screen Shoot Output


sumber : ilmuwebsite, w3school

0 komentar:

Posting Komentar

Template Design by Free template