How to Submit Form via Ajax using jQuery

Generally, the HTML form is submitted to the script URL specified in the action attribute of the <form> tag. You can also handle the form submission process using jQuery. The jQuery submit() method is very useful to handle the form submission process. In this example code snippet, we will show you how to submit an HTML form via Ajax using jQuery.

The following HTML form will be submitted via Ajax request with jQuery.

<form id="myFrmID" action="submit.php">
    <div class="form_outer">
        <div class="row">
            <div class="col-md-6">
                <div>
                    <label>First Name:</label>
                    <input type="text" name="first_name" id="first_name" value="">
                </div>
            </div>
            <div class="col-md-6">
                <div>
                    <label>Last Name:</label>
                    <input type="text" name="last_name" id="last_name" value="">
                </div>
            </div>
            <div class="col-md-12">
                <div>
                    <label>Message:</label>
                    <textarea name="message" id="message"></textarea>
                </div>
            </div>
            <div class="col-md-12">
                <div class="book_btn">
                    <button type="submit">Submit</button>
                </div>
            </div>
        </div>
    </div>
</form>

Use the following jQuery to submit the form with all the input field values via Ajax request to script URL mentioned in the <form> action.

$(document).ready(function(){
    $('#myFrmID').submit(function(e){
        e.preventDefault();
        
        var form = $(this);
        var actionUrl = form.attr('action');
        
        $.ajax({
            type: "POST",
            url: actionUrl,
            data: form.serialize(),
            dataType: "json",
            success:function(data){
                // Process with the response data
            }
        });
    });
});

Leave a reply

keyboard_double_arrow_up