How to submit HTML form without reloading the page (jQuery)

This is a simple example on how to submit HTML form data and display the response with PHP, without reloading the page (ajax request).
I will do it with the help of jquery javascript library. First step is to make sure jquery is loaded. If your document already uses jquery for something else, there is no need to include it again. If it doesn’t – just add this line to the head of your HTML document, to load jquery from Google CDN:

<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>

Then, we need the HTML form:

<form id="test-form" action="test.php" method="post">
    <div id="ajax-response"></div>
    <input name="nick" type="text" />
    <input name="message" type="text" />
    <input type="submit" value="Send!" />
</form>

Div with and id “ajax-response” will be used to display the response message.
File test.php is used for server side actions. In this case – it just displays what has been submitted to it.
File test.php

<pre>
<?php
echo htmlspecialchars(var_export($_REQUEST, true));
?>
</pre>

Now we need to add the code, which handles the ajax part. This code is somewhat universal, as it doesn’t have any fields or action url defined, it just uses what’s set in the HTML.

$(document).ready(function() {

    $('#test-form').on('submit', function(e) {
        e.preventDefault();

        $.ajax({
            type: $(this).attr('method'),
            url: $(this).attr('action'),
            data: $(this).serialize(),
            success: function(data) {
                $('#ajax-response').html(data); 
            }
        });

    });

});

Leave a Reply

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