Having a good comment section creates a good user experience in our blog. In this project, we are going to create a basic commenting system that consists of a form with two inputs; which are name and comment. A user can add a comment on the page without the page reloading (this is the function of Ajax) and this comment will be stored in the database.

All comments in the database are displayed on the same index page and the user can either delete or edit a comment by simply hovering over it and clicking on either the delete or edit button that appears on the comment section. Note: This also deletes or edits the comment without having to reload the page.

Features of the project

  1. Input comment 
  2. comment section
  3. edit comment
  4. delete comment

Let's do some work.
Create a project folder and call it ajax_crud. Inside this folder, create a file called index.php. Copy the below code and paste it there. Take note that we have included the controller.php file in the first line. This file includes our PHP functions that do the backend functionality.

ajax_crud.php

<?php include('controller.php'); ?>
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Insert and Retrieve data from MySQL database with ajax</title>
  <link rel="stylesheet" href="css/main.css?version1">
</head>
<body>
  <div class="wrapper">
    <h3>Simple CRUD System Developed Using PHP and Ajax</h3>
  	<?php echo $comments; ?>
  	<form class="comment_form">
      <div>
        <label for="name">Name:</label>
      	<input type="text" name="name" id="name" required>
      </div>
      <div>
      	<label for="comment">Comment:</label>
      	<textarea name="comment" id="comment" cols="30" rows="5" required></textarea>
      </div>
      <button type="button" id="submit_btn">POST</button>
      <button type="button" id="update_btn" style="display: none;">UPDATE</button>
  	</form>
  </div>

<!-- Add JQuery -->
<script src="js/jquery.min.js"></script>
<script src="js/scripts.js"></script>
</body>
</html>

We are going to create our CSS file main.css for the styling of the project. Create a folder called CSS in the root folder of our project and inside the CSS folder create a file called main.css and save the below code in there.

main.css:

.wrapper {
  width: 45%;
  height: auto;
  margin: 10px auto;
  border: 1px solid #cbcbcb;
  background: purple;
}
/*
* COMMENT FORM
**/
.comment_form {
  width: 80%;
  margin: 100px auto;
  border-radius: 50px;
  background: #fafcfc;
  padding: 20px;
}
.comment_form label {
  display: block;
  margin: 5px 0px 5px 0px;
}
.comment_form input, textarea {
  padding: 5px;
  border-radius: 10px;
  width: 95%;
}
#submit_btn, #update_btn {
  padding: 8px 15px;
  color: white;
  background: purple;
  border: none;
  border-radius: 10px;
  margin-top: 10px;
}
#update_btn {
  background: purple;
}
/*
* COMMENT DISPLAY AREA
**/
#display_area {
  width: 90%;
  padding-top: 15px;
  margin: 10px auto;
}
.comment_box {
  cursor: default;
  margin: 5px;
  border-radius: 10px;
  padding: 5px 10px;
  position: relative;
  background: white;
}
.delete {
  position: absolute;
  top: 0px;
  right: 3px;
  color: red;
  display: none;
  cursor: pointer;
}
.edit {
  position: absolute;
  top: 0px;
  right: 45px;
  color: green;
  display: none;
  cursor: pointer;
}
.comment_box:hover .edit, .comment_box:hover .delete {
  display: block;
}
.comment_text {
  text-align: justify;
}
.display_name {
  color: blue;
  padding: 0px;
  margin: 0px 0px 5px 0px;
}

h3{
  text-align: center;
  color: white;
}

Ajax is a JQuery technology that is required in this project. Go to the JQuery website and download the JQuery file from there. 
Now let us add the Javascript. The Javascript is responsible for sending a request with data to the controller when a user clicks on the button. Create a folder called js in the root folder of our project and inside the js folder create a file called scripts.css and save the below codes in there.

script.js:

$(document).ready(function(){
  // save comment to database
  $(document).on('click', '#submit_btn', function(){
    var name = $('#name').val();
    var comment = $('#comment').val();
    $.ajax({
      url: 'controller.php',
      type: 'POST',
      data: {
        'save': 1,
        'name': name,
        'comment': comment,
      },
      success: function(response){
        $('#name').val('');
        $('#comment').val('');
        $('#display_area').append(response);
      }
    });
  });
  // delete from database
  $(document).on('click', '.delete', function(){
  	var id = $(this).data('id');
  	$clicked_btn = $(this);
  	$.ajax({
  	  url: 'controller.php',
  	  type: 'GET',
  	  data: {
    	'delete': 1,
    	'id': id,
      },
      success: function(response){
        // remove the deleted comment
        $clicked_btn.parent().remove();
        $('#name').val('');
        $('#comment').val('');
      }
  	});
  });
  var edit_id;
  var $edit_comment;
  $(document).on('click', '.edit', function(){
  	edit_id = $(this).data('id');
  	$edit_comment = $(this).parent();
  	// grab the comment to be editted
  	var name = $(this).siblings('.display_name').text();
  	var comment = $(this).siblings('.comment_text').text();
  	// place comment in form
  	$('#name').val(name);
  	$('#comment').val(comment);
  	$('#submit_btn').hide();
  	$('#update_btn').show();
  });
  $(document).on('click', '#update_btn', function(){
  	var id = edit_id;
  	var name = $('#name').val();
  	var comment = $('#comment').val();
  	$.ajax({
      url: 'controller.php',
      type: 'POST',
      data: {
      	'update': 1,
      	'id': id,
      	'name': name,
      	'comment': comment,
      },
      success: function(response){
      	$('#name').val('');
      	$('#comment').val('');
      	$('#submit_btn').show();
      	$('#update_btn').hide();
      	$edit_comment.replaceWith(response);
      }
  	});		
  });
});

Now, For the controller file, in the root folder create a file and name it controller.php. Copy the below code and paste it there.

controller.php

<?php 
  $conn = mysqli_connect('localhost', 'root', '', 'crud_ajax');
  if (!$conn) {
    die('Connection failed ' . mysqli_error($conn));
  }
  if (isset($_POST['save'])) {
    $name = $_POST['name'];
  	$comment = $_POST['comment'];
  	$sql = "INSERT INTO comments (name, comment) VALUES ('{$name}', '{$comment}')";
  	if (mysqli_query($conn, $sql)) {
  	  $id = mysqli_insert_id($conn);
      $saved_comment = '<div class="comment_box">
      		<span class="delete" data-id="' . $id . '" >delete</span>
      		<span class="edit" data-id="' . $id . '">edit</span>
      		<div class="display_name">'. $name .'</div>
      		<div class="comment_text">'. $comment .'</div>
      	</div>';
  	  echo $saved_comment;
  	}else {
  	  echo "Error: ". mysqli_error($conn);
  	}
  	exit();
  }
  // delete comment fromd database
  if (isset($_GET['delete'])) {
  	$id = $_GET['id'];
  	$sql = "DELETE FROM comments WHERE id=" . $id;
  	mysqli_query($conn, $sql);
  	exit();
  }
  if (isset($_POST['update'])) {
  	$id = $_POST['id'];
  	$name = $_POST['name'];
  	$comment = $_POST['comment'];
  	$sql = "UPDATE comments SET name='{$name}', comment='{$comment}' WHERE id=".$id;
  	if (mysqli_query($conn, $sql)) {
  		$id = mysqli_insert_id($conn);
  		$saved_comment = '<div class="comment_box">
  		  <span class="delete" data-id="' . $id . '" >delete</span>
  		  <span class="edit" data-id="' . $id . '">edit</span>
  		  <div class="display_name">'. $name .'</div>
  		  <div class="comment_text">'. $comment .'</div>
  	  </div>';
  	  echo $saved_comment;
  	}else {
  	  echo "Error: ". mysqli_error($conn);
  	}
  	exit();
  }

  // Retrieve comments from database
  $sql = "SELECT * FROM comments";
  $result = mysqli_query($conn, $sql);
  $comments = '<div id="display_area">'; 
  while ($row = mysqli_fetch_array($result)) {
  	$comments .= '<div class="comment_box">
  		  <span class="delete" data-id="' . $row['id'] . '" >delete</span>
  		  <span class="edit" data-id="' . $row['id'] . '">edit</span>
  		  <div class="display_name">'. $row['name'] .'</div>
  		  <div class="comment_text">'. $row['comment'] .'</div>
  	  </div>';
  }
  $comments .= '</div>';
?><?php 
  $conn = mysqli_connect('localhost', 'root', '', 'crud_ajax');
  if (!$conn) {
    die('Connection failed ' . mysqli_error($conn));
  }
  if (isset($_POST['save'])) {
    $name = $_POST['name'];
    $comment = $_POST['comment'];
    $sql = "INSERT INTO comments (name, comment) VALUES ('{$name}', '{$comment}')";
    if (mysqli_query($conn, $sql)) {
      $id = mysqli_insert_id($conn);
      $saved_comment = '<div class="comment_box">
          <span class="delete" data-id="' . $id . '" >delete</span>
          <span class="edit" data-id="' . $id . '">edit</span>
          <div class="display_name">'. $name .'</div>
          <div class="comment_text">'. $comment .'</div>
        </div>';
      echo $saved_comment;
    }else {
      echo "Error: ". mysqli_error($conn);
    }
    exit();
  }
  // delete comment fromd database
  if (isset($_GET['delete'])) {
    $id = $_GET['id'];
    $sql = "DELETE FROM comments WHERE id=" . $id;
    mysqli_query($conn, $sql);
    exit();
  }
  if (isset($_POST['update'])) {
    $id = $_POST['id'];
    $name = $_POST['name'];
    $comment = $_POST['comment'];
    $sql = "UPDATE comments SET name='{$name}', comment='{$comment}' WHERE id=".$id;
    if (mysqli_query($conn, $sql)) {
      $id = mysqli_insert_id($conn);
      $saved_comment = '<div class="comment_box">
        <span class="delete" data-id="' . $id . '" >delete</span>
        <span class="edit" data-id="' . $id . '">edit</span>
        <div class="display_name">'. $name .'</div>
        <div class="comment_text">'. $comment .'</div>
      </div>';
      echo $saved_comment;
    }else {
      echo "Error: ". mysqli_error($conn);
    }
    exit();
  }

  // Retrieve comments from database
  $sql = "SELECT * FROM comments";
  $result = mysqli_query($conn, $sql);
  $comments = '<div id="display_area">'; 
  while ($row = mysqli_fetch_array($result)) {
    $comments .= '<div class="comment_box">
        <span class="delete" data-id="' . $row['id'] . '" >delete</span>
        <span class="edit" data-id="' . $row['id'] . '">edit</span>
        <div class="display_name">'. $row['name'] .'</div>
        <div class="comment_text">'. $row['comment'] .'</div>
      </div>';
  }
  $comments .= '</div>';
?>

Create a database called crud_ajax. In that database, create a table called comments with the following fields in it:

  1. id - int(11)
  2. name - varchar(255)
  3. comment - text
Note: You can download the full source code and do the installation yourself. 

Requirements

  1. Download and Install any local web server such as XAMPP/WAMP.
  2. Download the provided source code zip file. (download button is located below)

Installation/Setup

  1. Open your XAMPP/WAMP's Control Panel and start Apache and MySQL.
  2. Extract the downloaded source code zip file.
  3. If you are using XAMPP, copy the ajax_crud folder from the extracted source code folder and paste it into the XAMPP's "htdocs" directory. And If you are using WAMP, paste it into the "www" directory.
  4. Open your XAMPP/WAMP PHPMyAdmin in a browser and create a new database naming crud_ajax.
  5. Import the provided SQL file into your newly created database. The file is located inside the database folder and is known as crud_ajax.sql.
  6. Browse the Image Preview System in a browser. i.e. http://localhost/ajax_crud.