How can I update a string using PHP without reloading the page, similar to AJAX functionality?

Solution 1: Conceptual Explanation

1. PHP runs on the server, not in the browser.

2. Once PHP generates a page and sends it to the browser, it can’t update the page on its own.

3. To update content without reloading, you need JavaScript (usually via AJAX).

4. JavaScript makes a request to a PHP script, gets the response, and updates the page dynamically.

Solution:2
Front-End (HTML + jQuery)


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>AJAX Form Submission</title>
  <script src="jquery-1.7.1.min.js"></script>
  <script>
    $(document).ready(function () {
      $("form#submit").submit(function (e) {
        e.preventDefault(); // Prevent default form submission

        // Get form values
        const fname = $('#fname').val();
        const lname = $('#lname').val();

        // Send data via AJAX
        $.ajax({
          type: "POST",
          url: "ajax.php",
          data: { fname: fname, lname: lname },
          success: function () {
            $('form#submit').hide(function () {
              $('div.success').fadeIn();
            });
          },
          error: function () {
            alert("Error submitting form. Please try again.");
          }
        });
      });
    });
  </script>
</head>
<body>
  <form id="submit" method="post">
    <fieldset>
      <legend>Enter Information</legend>

      <label for="fname">Client First Name:</label>
      <input id="fname" class="text" type="text" name="fname" size="20" required />

      <label for="lname">Client Last Name:</label>
      <input id="lname" class="text" type="text" name="lname" size="20" required />

      <button type="submit" class="button positive">Add Client</button>
    </fieldset>
  </form>

  <div class="success" style="display: none;">
    Client has been added successfully.
  </div>
</body>
</html>

Back-End (PHP Script – ajax.php)


<?php
include("../../inc/config.inc.php");

// Create connection (adjust $conn if your config file already sets it)
$conn = new mysqli($db_host, $db_user, $db_pass, $db_name);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Collect and sanitize input
$fname = trim($_POST['fname']);
$lname = trim($_POST['lname']);

// Prepare and bind (to prevent SQL injection)
$stmt = $conn->prepare("INSERT INTO clients (fname, lname) VALUES (?, ?)");
$stmt->bind_param("ss", $fname, $lname);

// Execute query
if ($stmt->execute()) {
    echo "success";
} else {
    echo "error: " . $stmt->error;
}

$stmt->close();
$conn->close();
?>