Thursday, June 16, 2011

LEARN HOW TO CREATE COMMENT SYSTEM WITH PHP AND JQUERY

first create table and call it "comment" with 3 fields id, name and comment

mysql.php 

<?php 
@mysql_connect("localhost","root","") or die ("could not connect to mysql");
@mysql_select_db("name of your database") or die ("no database");
?>
///////////page end here

index.php

<?php 
include_once "mysql.php";
//////render data that is already stored in the data base
 $sql_comments = mysql_query("SELECT * FROM comment ORDER BY id DESC");
while($row = mysql_fetch_array($sql_comments)){
 $name = $row["name"];
 $comment = $row["comment"];
 
 $commentlist .= 'name : '.$name.'<br />comment : '.$comment.'<hr>';
}
//////////////
?>

<script type="text/javascript" src="js/jquery-1.4.2.js"></script>
<script type="text/javascript">
$(document).ready(function(){
 $('#loading').hide();
});

function wall(){
$('#loading').show();

  var name = $('#name').val();///#name is the input id from the form and will be equal the variable "name"
  var comment = $('#comment').val();/////#comment is textarea id from the form and will be equal the variable "comment"
  var URL = "post.php"; /////post.php will be equal the variable "comment"
  
  $.post(URL,{wall:"post",name1:name,comment1:comment},function(data){//parameter wall will be equal "post", name1 will be equal to the var "name" and comment1 will be equal to the var "comment"
  $("#result").prepend(data).show();// the result will be placed above the the #result div
  $('#loading').hide();
  });
 }
</script>

<table width="500" border="0" align="center" cellpadding="0" cellspacing="0">
  <tr>
    <td><div id='form'><form>
    name<br />
      <input type="text" id="name" />
      <br />
   comment<br />
      <textarea id="comment" cols="45" rows="5"></textarea>
      <br />
      <input type="submit" name="button" id="button" value="Submit" onclick="return false" onmousedown="javascript:wall();"/><img src="loading.gif" alt="" width="15" height="15" id="loading" />
      <br /></form>
    </div>
      <div id="result"><?php print"$commentlist";?></div></td>
  </tr>
</table>

post.php 
<?php
include_once "mysql.php";
  if ($_POST['wall'] == "post"){
  $name = $_POST['name1'];//name1 is parameter from the jquery function  
  $comment = $_POST['comment1'];//comment1 is parameter from the jquery function  
   if ($comment=="" || $name==""){exit();}// if no name or comment exit the script
   else{
   //insert the name and comment into database 
  $sql = mysql_query("INSERT INTO comment (name,comment) 
     VALUES('$name','$comment')")
     or die (mysql_error());  
// the inserted comment will renderd by the "$("#result").prepend(data).show();" from jquery
echo 'name : '.$name.'<br />comment : '.$comment.'<hr>';
 }
}
?>

7 comments: