How to Submit a Form Using jQuery ?

How to Submit a Form Using jQuery ?

Asked on November 2, 2018 in jQuery.
Add Comment


  • 2 Answer(s)

    The jQuery submit() Method

    The submit() method to submit an HTML form (i.e. <form>) using jQuery.

    The jQuery code in the following example will submit the form on click of the button (i.e. the <button> element)

    which has the type attribute set to button

    <!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>jQuery Form Submit</title>
    <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
    <script>
    $(document).ready(function(){
            $("#submitBtn").click(function()
        {
            $("#myForm").submit(); // Submit the form
        });
    });
    </script>
    </head>
    <body>
         <form action="action.php" method="post" id="myForm">
            <label>First Name:</label>
           <input type="text" name="first-name">
          <button type="button" id="submitBtn">Submit Form</button>
        </form>
    </body>
    </html>
    
    Answered on November 2, 2018.
    Add Comment

    Examples:

    Normal

    $('form#myForm').submit();

    AJAX

    $('input#submitButton').click( function() {
        $.post( 'some-url', $('form#myForm').serialize(), function(data) {
             ... do something with response from server
           },
           'json' // I expect a JSON response
        );
    });
    
    $('input#submitButton').click( function() {
        $.ajax({
            url: 'some-url',
            type: 'post',
            dataType: 'json',
            data: $('form#myForm').serialize(),
            success: function(data) {
                       ... do something with the data...
                     }
        });
    });

    Note that the ajax() and post() methods above are equivalent. There are additional parameters you can add to the ajax() request to handle errors, etc.

    Answered on February 25, 2019.
    Add Comment


  • Your Answer

    By posting your answer, you agree to the privacy policy and terms of service.