Core PHP

Post a Form Comment with AJAX

This PHP example program demonstrates how to post a comment via AJAX and a form.

PostComment.html

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>XoaX.net's JavaScript and PHP</title>
    <style>
      #idComment {
        width:300px;
        height:300px;
        border:1px black solid;
        padding:5px;
        overflow:auto;
      }
    </style>
    <script>
function PostComment() {
    // Creating the XMLHttpRequest object
    var request = new XMLHttpRequest();

    // Instantiating the request object
    request.open("POST", "ProcessComment.php");

    // Defining event listener for readystatechange event
    request.onreadystatechange = function() {
        // Check if the request is compete and was successful
        if(this.readyState === 4 && this.status === 200) {
            // Inserting the response from server into an HTML element
            document.getElementById("idComment").innerHTML = this.responseText;
        }
    };

    // Retrieving the form data
    var myForm = document.getElementById("myForm");
    var formData = new FormData(myForm);

    // Sending the request to the server
    request.send(formData);
}
    </script>
  </head>
  <body>
    <form id="myForm">
      <label>Name:</label>
      <div><input type="text" name="keyName"></div>
      <br>
      <label>Comment:</label>
      <div><textarea name="keyComment"></textarea></div>
      <p><button type="button" onclick="PostComment()">Post Comment</button></p>
    </form>
    <div id="idComment">
      <p>Comments are displayed here.</p>
    </div>
  </body>
</html>
 

ProcessComment.php

<?php
if($_SERVER["REQUEST_METHOD"] == "POST") {
    $sName = htmlspecialchars(trim($_POST["keyName"]));
    $sComment = htmlspecialchars(trim($_POST["keyComment"]));

    // Check if form fields values are empty
    if(!empty($sName) && !empty($sComment)) {
        echo "<p>Hello, <b>$sName</b>. Your comment has been posted.<p>";
        echo "<p><b>$sName</b> said, <q><b>$sComment</b></q></p>";
    } else {
        echo "<p>Please fill all the fields in the form!</p>";
    }
} else {
    echo "<p>Something went wrong. Please try again.</p>";
}
?>
 

Output

 
 

© 2007–2025 XoaX.net LLC. All rights reserved.