How to create a simple comment script. Simple commenting system using AJAX. Facebook comments: pros and cons

In this lesson I will talk about how comments are made in HTML, CSS, PHP. Comments are text that is not visible on the web page. They are used for various kinds of explanations, reminders, and descriptions for webmasters, which allows you to structure the document. Comments are indispensable when debugging code; they allow you to quickly navigate the markup of a web page and find the desired block. Comments are often used to debug HTML code. For example, you can temporarily comment out a specific block of code so that it is not executed, and if necessary, you can easily restore it.

Comments in HTML

In HTML, comments are formed using the characters: . Thus, any text between these characters is a comment. Let's look at an example:

Example of comments in HTML

Comments in CSS

Comments in CSS are created using the characters: /* and */. To create a comment, you simply need to place the web page code between these characters:

/* Start of a block with styles for Body*/ body ( background: #efeded; font-family: Verdana, Helvetica, sans-serif; font-size: 12px; margin: 0px; padding: 0px; ) /* End of a block with styles for Body*/ Comments in PHP

Comments in PHP can be single-line or multi-line:

1) Single-line comments in PHP are created using the characters: //. Simply put this character in front of the line and it will be commented out. This option is used in the case when the comment consists of only one line.

2) To implement multi-line comments, the following symbols are used: /* and */. This option is useful if the comment spans several lines.

So we learned to do

This time we are making a simple AJAX commenting system. This will demonstrate how to achieve efficient interoperability between JQuery and PHP/MySQL using JSON. The system works in such a way that added comments are placed on the page without it. full reboot, giving the feeling of the site running only on the user's computer, thereby avoiding the need to wait for some time required to reload the page with the added comment.

Here's a rough demo of what we plan to implement:

Step 1 - XHTML

First, let's take a look at the comment markup. This code is generated by PHP in a comment, which we're going to look at in a moment.

Demo.php Name July 30, 2010

A comment

The Div of the avatar class contains a hyperlink corresponding to the avatar (if the user specified a valid link to the avatar when sending a comment), for example from gravatar.com. Well, we'll come back to this when we work with PHP. Finally, we have the name and time also in the DIVs, as well as the comment, that is, the text itself in the paragraph.

Another important element in the XHTML part is the comment submission form itself (all fields except the URL field are required).

Demo.php

Add a comment

Your name? Your Email?

What is your avatar? (optional) What did you want to say?

Step 2 - PHP PHP handles database connections MySQL data

and creates comment markup. In addition, AJAX is used at the end and inserts a comment into the comments table. You can see the code that displays comments on the page below.

Demo.php /* / Select all comments and fill the $comments array */ $comments = array(); $result = mysql_query("SELECT * FROM comments ORDER BY id ASC"); while($row = mysql_fetch_assoc($result)) ( $comments = new Comment($row); )

The MySQL query fetches all entries from the database and populates the $comments array with the comment class object you see below. This array is output after the script is executed.

Demo.php /* / Display comments one by one */ foreach($comments as $c)( echo $c->markup(); )

Each comment has a markup() method, which generates HTML code for printing the page. You can see this method and class below.

Comment.class.php – Step 1 class Comment ( private $data = array(); public function __construct($row) ( /* / Constructor */ $this->data = $row; ) public function markup() ( / */ This method outputs the XHTML comment markup */ // Create an alias so we don't have to // write $this->data data every time: $d = &$this->data $link_open = ""; = ""; if($d["url"])( // If the person filled in the URL when // adding a comment // Define the hyperlink $link_open = ""; $link_close = ""; ) // Time conversion $d[ "dt"] = strtotime($d["dt"]); // Required for default Gravatar images: $url = "http://".dirname($_SERVER["SERVER_NAME"]. $_SERVER["REQUEST_URI "])."/img/default_avatar.gif"; return " ".$link_open." ".$link_close."

".$link_open.$d["name"].$link_close."

1, "html"=>$insertedComment->markup())); ) else ( /* Display error messages */ echo "("status":0,"errors":". json_encode($arr).")""; )

submit.php receives the comment data as an AJAX request. It checks it and produces a JSON object, either the XHTML markup that was successfully rendered, or a list of error messages. JQuery uses ownership status to determine whether error messages should be displayed or a page markup comment should be added.

You can see two examples below. Step 1 - XHTML First, let's look at the comment markup. This code .

generated by PHP with class Comment

demo.php

Username 30 Jun 2010 Comment text div Username 30 Jun 2010 avatar Username 30 Jun 2010 contains a link (if the user entered the correct URL when posting a comment) and an avatar image, which we get from gravatar.com. We'll return to generating the markup in the PHP step. Finally follow name

time

and comment text.

Add a comment

Another important element in XHTML is the comment form. It is sent using POST. All fields except URL must be completed.

demo.php Name Email Website (optional) Comment Content The form is submitted using AJAX. The check is performed in background in submit.php . Each field has a corresponding element label.

, with the attribute set

for

demo.php /* / Select all comments and fill the $comments array with objects */ $comments = array(); $result = mysql_query("SELECT * FROM comments ORDER BY id ASC"); while($row = mysql_fetch_assoc($result)) ( $comments = new Comment($row); )

MySQL query selects all entries from the table and fills the $comments array with class objects comment. This array is displayed further when the script is executed.

demo.php /* / Print comments one by one: */ foreach($comments as $c)( echo $c->markup(); )

Each comment has a markup() method that generates the correct HTML code, ready to be displayed on the page. Below are the class and method definitions.

The class gets a row from the database (obtained using mysql_fetch_assoc()) and stores it in the $data variable. It is available only to the class method.

comment.class.php - Part 1 class Comment ( private $data = array(); public function __construct($row) ( /* / Constructor */ $this->data = $row; ) public function markup() ( / */ This method outputs XHTML markup for the comment */ // Set an alias so we don't have to write $this->data every time: $d = &$this->data; $link_open = "";

$link_close = "";

"; }

if($d["url"])( // If a URL was entered when adding a comment, // determine the opening and closing tags of the link $link_open = ""; $link_close = ""; ) // Convert the time to UNIX format: $d["dt"] = strtotime($d["dt"]);

// Needed to set the default image: $url = "http://".dirname($_SERVER["SERVER_NAME"].$_SERVER["REQUEST_URI"])."/img/default_avatar.gif";

comment.class.php - Part 2 public static function validate(&$arr) ( /* / This method is used to validate data sent via AJAX. / / It returns true/false depending on the correctness of the data, and fills / the $arr array , which is passed as a parameter either as data or as an error message. */ $errors = array(); $data = array(); // Use the filter_input function introduced in PHP 5.2.0 if(!($data["email" ] = filter_input(INPUT_POST,"email",FILTER_VALIDATE_EMAIL))) ( $errors["email"] = "Please enter a valid Email."; ) if(!($data["url"] = filter_input(INPUT_POST," url",FILTER_VALIDATE_URL))) ( // If an incorrect URL was entered in the URL field, // act as if the URL was not entered: $url = ""; ) // Use a filter with a callback function: if(!( $data["body"] = filter_input(INPUT_POST,"body",FILTER_CALLBACK,array("options"=>"Comment::validate_text")))) ( $errors["body"] = "Please enter the comment text ."; ) if(!($data["name"] = filter_input(INPUT_POST,"name",FILTER_CALLBACK,array("options"=>"Comment::validate_text")))) ( $errors["name" ] = "Please enter a name.";

) if(!empty($errors))( // If there are errors, copy the $errors array to $arr: $arr = $errors; return false; ) // If the data is entered correctly, clear the data and copy it to $arr : foreach($data as $k=>$v)( $arr[$k] = mysql_real_escape_string($v); ) // email must be in lowercase: $arr["email"] = strtolower(trim($ arr["email"]));

return true; ) The validate() method (also part of the class) is defined as static. This means that it can be called directly using the Comment::validate() construct, without creating a class object. This method checks the data that is sent via AJAX. The method uses new feature

filter, which became available in PHP 5.2.0. This way we can easily check and filter the data that is passed to the script. For example, filter_input(INPUT_POST,’url’,FILTER_VALIDATE_URL) means we are checking if $_POST["url"] is a valid URL. If so, then the function returns the value of the variable; otherwise, it returns false. Before using this function, you had to use). regular expressions to check data (using a series of designs

It is also possible to specify a function that will carry out additional data modifications.

comment.class.php - Part 3 private static function validate_text($str) ( /* / This method is used as FILTER_CALLBACK */ if(mb_strlen($str,"utf8")