Skip to content
PHP Logo

How can JavaScript or AJAX be used to handle form submission and processing in PHP instead of specifying an action attribute in the HTML form tag?

When using JavaScript or AJAX to handle form submission and processing in PHP instead of specifying an action attribute in the HTML form tag, you can use event listeners to capture the form submission event, prevent the default form submission behavior, serialize the form data, and send it to a PHP script using AJAX. The PHP script can then process the form data and return a response back to the JavaScript for further handling.

php
<?php
if ($_SERVER["REQUEST_METHOD"] == "POST") {
    // Process form data here
    $name = $_POST["name"];
    $email = $_POST["email"];

    // Return a response (e.g. JSON) back to the JavaScript
    $response = ["message" => "Form submitted successfully"];
    echo json_encode($response);
}
?>