Submitting Form Data with AJAX and jQuery

We will send form data without reloading the page using jQuery. We will not consider processing the server part.

Sample form:

<form id="test_ajax_form" method="post" action="test_handler_form.php">
    <input type="text" name="name" placeholder="Name">
    <textarea name="message" placeholder="Message"></textarea>
    <input type="submit" value="Send" name="submit">
</form>

JS

$(function(){
    $('#test_ajax_form').on('submit', function(e){
        e.preventDefault();
        let data = $(this).serialize(),
            url = $(this).attr('action');
 
        $.ajax({
            method: "POST",
            url: url,
            data: data
        }).done(function(){
            alert('Success!');
        }).fail(function(){
            alert('Error!');
        });
    });
});

Comments

Popular posts from this blog

Typical gulpfile.js

JavaScript Inheritance and Classes

Cheat sheet for work with Git