Comments with jQuery and JSON

Asynchronous Comments with PHP, jQuery, and JSON

In this article, we’re going to look at how we create a simple but effective means of capturing and displaying visitor comments using a blend of jQuery, PHP and JSON. In the public forum that is the blogosphere, the ability to capture and display visitor comments on your blogs can give you instant feedback and opinions from the people that matter most – those that read your blog.

Outline

We’ve several tasks that need to be accomplished in order to complete this example; when the page on which the comments are displayed is initially loaded, we need to display all of the existing comments. Additionally, when a new comment is made, we’ll need to display this on the page after the existing comments, as well as sending the new comment to the server for storage with the existing comments.

Tools Required

We’ll be using jQuery (version 1.3.1), obviously, because it rocks, and we’ll be using JSON because it’s a light-weight and efficient format for transporting data across networks. We’ll also be using a little simple PHP to interact with a MySQL database. You’ll need to have access to an installation of MySQL server and should prepare a new database called comments that contains a table, also called comments, which has a name column and a comment column. Running a select all query to your database should produce a result similar to that shown below:

demonstration

Getting Started – The Stored Comments

Let’s make a start by creating the PHP file that reads the comments from the database and returns them to the page; this way, when we come to code the page, the data will already be available for us to use. In a new file in your text editor add the following code:

<?php

  //db connection detils
  $host = "localhost";
  $user = "root";
  $password = "your_password_here";
  $database = "comments";
	
  //make connection
  $server = mysql_connect($host, $user, $password);
  $connection = mysql_select_db($database, $server);
	
  //query the database
  $query = mysql_query("SELECT * FROM comments");
	
    //loop through and return results
  for ($x = 0, $numrows = mysql_num_rows($query); $x < $numrows; $x++) {
    $row = mysql_fetch_assoc($query);
    
    $comments[$x] = array("name" => $row["name"], "comment" => $row["comment"]);		
  }
	
  //echo JSON to page
  $response = $_GET["jsoncallback"] . "(" . json_encode($comments) . ")";
  echo $response;  

?>

Save this as comments.php. Let’s briefly walk through what we do with this code. We store the access credentials for our server in the first four variables and following this, we connect to the database. We then query the database and select all of the data from it.

For Loop

In the next section of code we use a for loop to cycle through each row of data. On each iteration of the loop we add a new item to an array ($comments). The array is a multidimensional associate array and each item will have two sub items which are given the keys name and comment, matching the columns in our table. The value of each item will be the data from each respective field in the current row.

JSON Encode

Finally we package up the completed JSON object in a GET request and then use the native PHP json_encode function to convert our array into a properly formatted JSON object. We’ll be using a JSONP callback in the JavaScript, which is why we need to use a get response and also why we wrap the JSON encoded array in brackets. To clarify the structure of the data that we’re returning, if we were writing it out manually we would do something like this:

([
  {name:"a name", comment:"a comment"},
  {name:"a name", comment:"a comment"},
  { etc }
])

This consists of a simple array, where each item in the array is an object. These inner objects each have two properties – author and comment, where the values of these properties are the data extracted from the text file. Nesting the inner objects in an array makes it extremely easy for us process the data with jQuery. The following screenshot shows how the JSON object will be interpreted by Firebug:

demonstration

Displaying the Stored Comments

Now that we have an object to work with, we can create the HTML page that will display the comments. In a new file in your text editor add the following mark-up:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
  <head>
    <link rel="stylesheet" type="text/css" href="comments.css">
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
    <title>Asynchronous Comments</title>
  </head>
  <body>
    <div id="content">
      <h2>Some Content</h2>
      <p>Lorem ipsum dolor...</p>
    </div>
    <div id="comments">
      <h2>Reader Comments</h2>
    </div>
    <div id="leaveComment">
      <h2>Leave a Comment</h2>
      <div class="row"><label>Your Name:</label><input type="text"></div>
      <div class="row"><label>Comment:</label><textarea cols="10" rows="5"></textarea></div>
      <button id="add">Add</button>
    </div>
    <script type="text/javascript" src="jquery-1.3.1.min.js"></script>
  </body>
</html>

Save this file as comments.html. Most of the mark-up is non-essential and is used to give the example some substance. On the page we have some dummy content, a container which the existing comments can be rendered into and some basic form elements used to leave a new comment. In the head of the page we link to a stylesheet and at the end of the body we link to the jQuery library.

CSS

The stylesheet used in this example is non-essential and is used simply to present the example neatly. It consists of the following CSS:

body { font-family:verdana; font-size:11px; color:#ffffff; }
#content {
  width:400px; height:195px; border:3px solid #000000; margin:0 auto 10px;
  font-size:13px; background-color:#575454;
}
#content p { padding:0 10px; }
#comments {
  width:400px; border:3px solid #000000; margin:0 auto 10px;
  padding-top:5px; background-color:#575454;
}
.comment {
  background-color:#d4d7d6; border:1px solid #000000;
  padding:5px 0 5px 5px; color:#000000;
}
#leaveComment {
  width:400px; border:3px solid #000000; margin:0 auto;
  overflow:hidden; position:relative; background-color:#575454;
}
h2 { text-align:center; margin:5px 0 10px; }
.row { padding-left:5px; margin-bottom:5px; clear:both; overflow:hidden; }
.row label {
  width:100px; text-align:right; margin-right:5px; display:block;
  float:left; font-weight:bold; padding-top:5px;
}
.row input, .row textarea, .row div {
  width:280px; display:block; float:left;
}
#add {
  position:absolute; bottom:5px; left:60px; font-weight:bold;
  font-size:10px;
}

Save this as comments.css in the same directory as the HTML page. I won’t cover exactly what this code does as it’s pretty trivial and is used purely for display purposes. It should cause the page to be displayed as follows:

demonstration

Javascript

Now we can add the JavaScript that will request the JSON object from the server, process it and display the comments. Directly after the link to jQuery add the following script block:

<script type="text/javascript">
  $(function() {
			
    //retrieve comments to display on page
    $.getJSON("comments.php?jsoncallback=?", function(data) {
				
      //loop through all items in the JSON array
      for (var x = 0; x < data.length; x++) {
					
        //create a container for each comment
        var div = $("<div>").addClass("row").appendTo("#comments");
						
        //add author name and comment to container			    
        $("<label>").text(data[x].name).appendTo(div);		   
        $("<div>").addClass("comment").text(data[x].comment).appendTo(div);
      }
    });			
  });			
</script>

Again this code is fairly trivial; when the page has loaded, we use the getJSON method to request the JSON object from the PHP file, specifying the path to the file as the first argument. We add the JSONP callback – ?jsoncallback=? – to the end of the URL and then specify an anonymous callback function as the second argument, which will be executed if and when the request returns successfully.

Within our callback we have a simple for loop which is used to loop through each item in the JSON array. For each item we create a container div which is given a class of row and is then appended to the main comments container div.

We then specify a label and set the text of the label to the value of the name property of the object in the current array item. After the label has been appended to the current container div, we create another div which is used to hold the value of the comment property. The comment is then appended to the current container div.

Now when we run the page, we should find that the comments from the database are displayed within the specified container div:

demonstration

Adding New Comments Asynchronously

For the final part of this tutorial we can see how easy it is to automatically insert a new comment after the existing comments, while at the same time sending the new comment to the server to be added to the database so that it can be displayed automatically when the page is next loaded. Add the following new code directly after the getJSON method:

//add click handler for button
$("#add").click(function() {
				
  //define ajax config object
  var ajaxOpts = {
    type: "post",
    url: "addComment.php",
    data: "&author=" + $("#leaveComment").find("input").val() + "&comment=" + $("#leaveComment").find("textarea").val(),
    success: function(data) {
							
      //create a container for the new comment
      var div = $("<div>").addClass("row").appendTo("#comments");
						
      //add author name and comment to container
      $("<label>").text($("#leaveComment").find("input").val()).appendTo(div);
      $("<div>").addClass("comment").text($("#leaveComment").find("textarea").val()).appendTo(div);
    }
  };
					
  $.ajax(ajaxOpts);
});

Again, this is very straight-forward code – what we’re doing is quite complex, but jQuery abstracts away all the difficulty and cross-browser trickiness, leaving us to write just a few lines of code. We first set a click handler for the add comment button. This will execute the anonymous function specified as an argument to the click method whenever the button is clicked.

Within this function we first create a new literal object which is used to configure the new AJAX request. We specify the type of request, the URL of the resource we’re requesting, some data and a success callback function. Within our success function all we do is get the contents of the input and textarea and add them to the comments div in the same way that we did with the original comment data received when the page loads.

Database Connection

We’ll need one more PHP file in order to write the new comment to the database:

<?php

  //db connection detils
  $host = "localhost";
  $user = "root";
  $password = "your_password_here";
  $database = "comments";
	
  //make connection
  $server = mysql_connect($host, $user, $password);
  $connection = mysql_select_db($database, $server);
	
  //get POST data
  $name = mysql_real_escape_string($_POST["author"]);
  $comment = mysql_real_escape_string($_POST["comment"]);

  //add new comment to database
  mysql_query("INSERT INTO comments VALUES(' $name ',' $comment ')");

?>

Save this file as addComment.php. We specify our connection information once more and connect to the database. We then get the data sent by our JavaScript from the $_POST superglobal variables and then use the mysql_query function to insert the new data into the table. Notice that we use the mysql_real_escape_string function to prevent any misuse of our database; although it’s unlikely that any harm could come from an attacker gaining access to this particular database, it’s always wise to sanitize any data before it is added.

Now we should find that when we add a comment, the new comment is displayed on the page, and subsequent reloads of the page will show the new comment:

demonstration

Summary

Asynchronous comments are made easy with a combination of jQuery, simple scripts and the lightweight and highly effective JSON format. Although this is just a basic example, to which we could do so much more, I think you’ll agree when I say that it’s easy to implement a basic, but robust solution to the capture and display of comments from your visitors.

To learn more from Dan Wellman, be sure to sign up for our Net Plus program, where you can read, among others, his in depth tutorial/screencast “Build an Advanced “Poll” jQuery Plugin”. Sign up now!

  • Subscribe to the NETTUTS RSS Feed for more daily web development tuts and articles.


Tags: jQuery
Note: Want to add some source code? Type <pre><code> before it and </code></pre> after it. Find out more
  • Rudy

    A good enhancement would be to make the code reusable, so you can use multiple comment areas on a page. (Such as, on a blog, where you’d have more than one post per page, and comments for each post.) Unless there is something already written on this site I haven’t found yet…

  • http://none manish

    really this code is very effective…

  • http://spotdex.com David Moreen

    I can not comprehend not easy this was. Simple functionality sure, but effective.

  • Pingback: Useful PHP & jQuery Components « Developer Suite

  • http://www.trcreative.co.uk trCreative Web Design

    Been looking for something like this for a while, thanks!

  • Pingback: Resources for PHP Webmail « David Woodfield

  • MK

    This is perfect! Everything (the basics) for what I need to create a web app I’ve been trying to figure out for a while. Thank you very much!

  • Pingback: Asynchronous Comments with PHP, jQuery, and JSON | Ajaxmint - Endless Ajax samples on jQuery, MooTools, ExtJS, Dojo, Prototype and PHP

  • http://websitelatenmaken website laten maken

    very nice article & very useful information too, but the demo isn’t working for me, it is starting from the basics & approaching to the goal in a smooth way
    Thanks
    website laten maken

  • http://www.resmarketing.ws RESMarketing.ws

    Very clever coding Dan. To avail the script for free is an unexpected bonus. Thank you.

  • Ben

    What’s the point in using ajax?

    • jhgj

      hgjghj

      • jas

        hi

      • jyoti

        dead in the water … comments.php works down to the JSON part then nothing. Tested my jQuery install good with a test page okay. Its okay … my problem was in my php includes I was trying to get to work. Once I did a test page according to the instructions above. Its

  • Pingback: 20 Useful PHP + jQuery Components & Tuts for Everyday Project | Dummies Garage V3

  • Pingback: 35 Really Useful PHP Tutorials And Development Techniques | Smashing Buzz

  • Pingback: 10 Essential PHP Code Snippets You Might be Looking For | DevSnippets

  • syskata

    i have to two record in databases and it’ show on page but when i press add button the comment show on page but it’s not store in databases. some one help

    • syskata

      fix it. the error was in mysql query

  • Pingback: 15+ Useful PHP & jQuery Components | WEBAXES.COM

  • Pingback: 30 Useful PHP Tutorials « Web Creation in Cambodia

  • Pingback: 60 Awesome jQuery Tutorials | Web.Dtuts - Web Development Tutorials

  • Pingback: 75+ jQuery Plugins: Download Powerful and Elegent jQuery Plugins & Tutorials | jQuery | Graphic Design Junction

  • Zeroel

    I have a question. What can be added so that you can have a delete function on the comments?

  • melvin

    Hi, an awesome tutorial. I hope you can help me out – I want to arrange the entries’ stacking order so that the most recent ones are placed on top – hope there’s an extra line of code that can make this happen everytime a new one is added and data request is refreshed. thank you and more power!

  • http://www.allsaudijobs.com Saudi Jobs

    Thanks for giving this tutorial because i am searching for this code.

  • saebabez
  • ADi OniZin

    Mr. Dan, I have problem to use it…
    Comment not working properly…

    my Step:
    >> copy paste & dowload the source code same with your order above.
    >> launch the comment.html
    >> filling the comment box…
    >> klik the “add” button…

    “no progress….”

    my suspect is in MySQL, I’m still don’t understand this tool function…I’m trying to type

    mysql> SELECT * FROM comment;
    ERROR 1046 : no database selected

    did I miss some thing…??
    please explain me more, I’m trying to make web site in Offline mode…(intranet)

    I’m Waiting you feed back…

    • http://test.com.au helper

      HI if your question hasnt been answered yet its because you need to change this part…

      $host = “localhost”;
      $user = “root”;
      $password = “your_password_here”;
      $database = “comments”;

      to reflect your database

  • Raju

    ‘jquery-1.3.1.min.js’ file is missing form source code zipped folder.

  • Pingback: 20 Useful PHP + jQuery Components & Tuts for Everyday Project « Simplification

  • http://www.airbatterycharger.com fujifilm battery

    Ah, I find the actual fact has limitless debatable points. I don’t wish to argue with you here, however I have my own opinions as well.fujifilm np-45 battery Anyway, you probably did an awesome job in writing the put up, and wish to reward you for the exhausting work. Sustain with the nice job!

  • http://www.youssefsiblini.com Jose

    Hi great tutorial thank you,

    Every thing is working good, but when I reload the page I lose all the comments but I can still see them in the database, pls can some one help.

  • http://www.youssefsiblini.com Jose

    Got it to work any way mant thanks again for the tutorial

  • Jason

    Love this website, already found a couple of the tutorials very useful!

    I’ve implemented this and it works great. However, I’m having a hard time implementing multiple comment boxes on a single page. The best way to describe what I’m doing is to think of a twitter stream, and the users having the ability to view comments and add comments on each individual tweet. So I added another column to the comments table called item_id which will reference which item this comment belongs too. I’m not sure how to implement this since every add button has the same id….any help is greatly appreciated!!

  • Pingback: 15 jQuery & PHP Combination Plugins | jQuery4u

  • Pingback: Good sample of asynchronous comment system for ASP.NET MVC, JSON and JQuery | deepinphp.com

  • http://www.ricardofilipe.com Ricardo

    I come a bit late, but thank you! This is such an easy and direct PHP/jQuery/JSON implementation that’s impossible not to follow along. I understand that you didn’t exactly use best practices methods, but the core works just fine.

    I’ve changed the event so it’s now a regular HTML form, so it listens for the form submit function and not a click of a button. This will make it easier to work with older browsers and those who still run the web with JS turned off. A quick reminder though, if you change the listener to a form, don’t forget to do two things:

    The first is to hold the default submission of the form, which will refresh the page. You can avoid this by writing return false at the end of your form submission function. The other thing is to change the button component to a regular input type=submit, otherwise IE7 will never fire up the submit event.

    Good work, thank you.

  • Pingback: Free jQuery Plugins Tutorails | Free download softwares, music, wordpress template, joomla template, Jquery tools and tips, Beauty tips, Free online video..

  • Pingback: how we create a simple visitor comments using a blend of jQuery « Javascript And Dhtml « Php « Codes php – Share your php snippets

  • http://www.surfholidays.com/destinations.aspx surf camps

    A great post which help a lot for me.. Since I am a newbie in this field

  • Porter Flirt

    I saw this really fantastic post today.Your blog post is very cogent and makes a number of good points.

  • http://mr-google.co.cc Seo Bolton

    Great post help me out alot. Thank U so much.

  • erick

    ‘jquery-1.3.1.min.js’ file is missing form source code zipped folder.

  • Matthew Hillman

    How would I adjust the code so the newest comment comes in on top and not underneath the previous comment?

    Also how can I add a fade effect for each comment when it comes in?

    Thanks in advance.

  • Anon

    Thanks a mil for this

  • Jag

    Well done!

  • Artek

    Thx very much. It’s helpful ;)

  • Kobena

    My database is empty. Can someone help? I am using the correct username and password for mysql database.

  • Kobena

    Solved the problem by using the sql code below instead of trying to create from phpmyadmin

    CREATE DATABASE comments;
    USE comments;

    CREATE TABLE comments (

    name VARCHAR(30) NOT NULL,
    comment LONGTEXT DEFAULT NULL
    )engine=myisam;

  • name

    test comment

  • http:topmoneynetwork.com/dev2/no73 Juan

    dead in the water … comments.php works down to the JSON part then nothing.

  • http:topmoneynetwork.com/dev2/no73 Juan

    dead in the water … comments.php works down to the JSON part then nothing. Tested my jQuery install good with a test page okay. Its okay … my problem was in my php includes I was trying to get to work. Once I did a test page according to the instructions above. Its A-OKAY!

  • Jake

    Keep in mind this has no SEO value since the comments are dynamically loaded, they don’t exist int he source and search engine spiders cannot read javascript loaded content.

  • user

    can you show ur comments system