Form submit in PHP without page refresh

Form submit in PHP without page refresh

Form submit in PHP without page refresh

Below is an example of an AJAX form submission using jQuery, PHP with a MySQL database connection, and client-side validation.

HTML Form (index.html):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AJAX Form Submit</title>
    <style>
        .error {
            color: red;
        }
    </style>
</head>
<body>
    <h1>Contact Form</h1>
    <form id="contactForm">
        <label for="name">Name:</label>
        <input type="text" name="name" id="name">
        <span id="nameError" class="error"></span>

        <label for="email">Email:</label>
        <input type="email" name="email" id="email">
        <span id="emailError" class="error"></span>

        <label for="message">Message:</label>
        <textarea name="message" id="message" rows="4"></textarea>
        <span id="messageError" class="error"></span>

        <button type="button" onclick="submitForm()">Submit</button>
    </form>

    <div id="result"></div>

    <script src="https://code.jquery.com/jquery-3.6.4.min.js"></script>
    <script>
        function submitForm() {
            // Reset errors
            $(".error").text("");

            // Get form data
            var formData = {
                name: $("#name").val(),
                email: $("#email").val(),
                message: $("#message").val()
            };

            // Validate form data (client-side)
            if (formData.name.trim() === "") {
                $("#nameError").text("Name is required.");
                return;
            }

            if (formData.email.trim() === "") {
                $("#emailError").text("Email is required.");
                return;
            }

            if (formData.message.trim() === "") {
                $("#messageError").text("Message is required.");
                return;
            }

            // Make AJAX request
            $.ajax({
                type: "POST",
                url: "submit.php",
                data: formData,
                success: function(response) {
                    $("#result").html(response);
                }
            });
        }
    </script>
</body>
</html>

PHP Script (submit.php):

<?php
// Database connection details
$host = "your_database_host";
$username = "your_database_username";
$password = "your_database_password";
$database = "your_database_name";

// Create a PDO connection
try {
    $pdo = new PDO("mysql:host=$host;dbname=$database", $username, $password);
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
    die("Database connection failed: " . $e->getMessage());
}

if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Retrieve form data
    $name = $_POST["name"];
    $email = $_POST["email"];
    $message = $_POST["message"];

    // Validate form data (server-side)
    if (empty($name) || empty($email) || empty($message)) {
        echo "All fields are required.";
        exit;
    }

    // Insert data into the database
    $stmt = $pdo->prepare("INSERT INTO contact_form (name, email, message) VALUES (?, ?, ?)");
    $stmt->execute([$name, $email, $message]);

    // Example: Just echoing the submitted data
    echo "Name: $name<br>";
    echo "Email: $email<br>";
    echo "Message: $message<br>";
} else {
    // Handle the case where the request method is not POST
    echo "Invalid request method.";
}
?>

In this example:

  • The HTML form includes basic client-side validation.
  • The jQuery script sends an AJAX POST request to submit.php.
  • submit.php validates the data server-side and inserts it into a MySQL database.
     




Mahendra Pratap Singh

Hey there! I'm a Senior Full Stack Developer with 10 +years of experience in the tech world. I've spent a lot of time working with different tools and languages, like PHP, WordPress, Laravel, and CodeIgniter... Read More >>

1 Comments

  • Deepak singh

    8 February, 2024 07:02:59 AM

    More help by this post.

    • Tutorialsonweb Team

      8 February, 2024 07:08:51 AM

      thanks deepak.

Leave a Comment