Simple jQuery AJAX and PHP Form Example

Last updated on | 2 replies

Here’s a simple example of an AJAX form using jQuery. Just create a new file my_form.html and paste in the code below.

This AJAX form sends a request to form.php, which will then output a response for AJAX.

my_form.html

<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery AJAX form example</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>

<script type="text/javascript">
    $(function() {
        // Variable to hold request
        var request;

        // Bind to the submit event of our form
        $("#my_form").submit(function(event){

            // Prevent default posting of form - put here to work in case of errors
            event.preventDefault();

            // Abort any pending request
            if (request) {
                request.abort();
            }
            // setup some local variables
            var $form = $(this);

            // Let's select and cache all the fields
            var $inputs = $form.find("input, select, button, textarea");

            // Serialize the data in the form
            var serializedData = $form.serialize();

            // Let's disable the inputs for the duration of the Ajax request.
            // Note: we disable elements AFTER the form data has been serialized.
            // Disabled form elements will not be serialized.
            $inputs.prop("disabled", true);

            // Fire off the request to /form.php
            request = $.ajax({
                url: "form.php",
                type: "post",
                data: serializedData
            });

            // Callback handler that will be called on success
            request.done(function (response, textStatus, jqXHR){
                // Log a message to the console
                console.log("Hooray, it worked!");
                $( "span#response" ).text('AJAX Response: ' + response)
            });

            // Callback handler that will be called on failure
            request.fail(function (jqXHR, textStatus, errorThrown){
                // Log the error to the console
                console.error(
                    "The following error occurred: "+
                    textStatus, errorThrown
                );
            });

            // Callback handler that will be called regardless
            // if the request failed or succeeded
            request.always(function () {
                // Reenable the inputs
                $inputs.prop("disabled", false);
            });

        });
    });
    </script>

</head>
<body>

<form id="my_form">
    <label for="message">Enter something: </label>
    <input id="message" name="message" type="text" value="" />
    <input type="submit" value="submit" />
    <span id="response"></span>
</form>
</body>
</html>

form.php

You will also need a simple PHP script to send back a test response. Create a file called form.php and place it in the same folder as my_form.html.

<?php
echo print_r($_POST,true);

Let me know if this helped. Follow me on Twitter, Facebook and YouTube, or 🍊 buy me a smoothie.

2 replies

Leave a reply

Your email address will not be published. Required fields are marked *

  1. This code example is the most comprehensive and easy learining JQuery form post code on the internet.

    Thanks really for writng and time.

  2. When I saved the files on Windows it didn’t work, and I have PHP installed.
    I uploaded to my server (via FTP) and voila!
    Thanks a lot!