533

I want to submit a form using jQuery. Can someone provide the code, a demo or an example link?

Dharman
  • 30,962
  • 25
  • 85
  • 135
mehul
  • 5,569
  • 3
  • 17
  • 8

22 Answers22

536

It depends on whether you are submitting the form normally or via an AJAX call. You can find lots of information at jquery.com, including documentation with examples. For submitting a form normally, check out the submit() method to at that site. For AJAX, there are many different possibilities, though you probably want to use either the ajax() or post() methods. Note that post() is really just a convenient way to call the ajax() method with a simplified, and limited, interface.

A critical resource, one I use every day, that you should bookmark is How jQuery Works. It has tutorials on using jQuery and the left-hand navigation gives access to all of the documentation.

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.

Dave Powers
  • 2,051
  • 2
  • 30
  • 34
tvanfosson
  • 524,688
  • 99
  • 697
  • 795
139

You will have to use $("#formId").submit().

You would generally call this from within a function.

For example:

<input type='button' value='Submit form' onClick='submitDetailsForm()' />

<script language="javascript" type="text/javascript">
    function submitDetailsForm() {
       $("#formId").submit();
    }
</script>

You can get more information on this on the Jquery website.

Appulus
  • 18,630
  • 11
  • 38
  • 46
Draco
  • 16,156
  • 23
  • 77
  • 92
84

when you have an existing form, that should now work with jquery - ajax/post now you could:

  • hang onto the submit - event of your form
  • prevent default functionality of submit
  • do your own stuff

    $(function() {
        //hang on event of form with id=myform
        $("#myform").submit(function(e) {
    
            //prevent Default functionality
            e.preventDefault();
    
            //get the action-url of the form
            var actionurl = e.currentTarget.action;
    
            //do your own request an handle the results
            $.ajax({
                    url: actionurl,
                    type: 'post',
                    dataType: 'application/json',
                    data: $("#myform").serialize(),
                    success: function(data) {
                        ... do something with the data...
                    }
            });
    
        });
    
    });
    

Please note that, in order for the serialize() function to work in the example above, all form elements need to have their name attribute defined.

Example of the form:

<form id="myform" method="post" action="http://example.com/do_recieve_request">

<input type="text" size="20" value="default value" name="my_input_field">
..
.
</form>

@PtF - the data is submitted using POST in this sample, so this means you can access your data via

 $_POST['dataproperty1'] 

, where dataproperty1 is a "variable-name" in your json.

here sample syntax if you use CodeIgniter:

 $pdata = $this->input->post();
 $prop1 = $pdata['prop1'];
 $prop1 = $pdata['prop2'];
Koen Hollander
  • 1,687
  • 6
  • 27
  • 42
womd
  • 3,077
  • 26
  • 20
73

In jQuery I would prefer the following:

$("#form-id").submit()

But then again, you really don't need jQuery to perform that task - just use regular JavaScript:

document.getElementById("form-id").submit()
gernberg
  • 2,587
  • 17
  • 21
  • 1
    @windmaomao I had the same issue. My jQuery ran all other functions, but would not submit the form. It worked by just using the document.getElementById method. – ChallengeAccepted May 25 '16 at 02:12
52

From the manual: jQuery Doc

$("form:first").submit();
Jens
  • 8,423
  • 9
  • 58
  • 78
AdamSane
  • 2,831
  • 1
  • 24
  • 28
  • 5
    It is batter to submit form by "id' than finding the first form and submit it. However it will works perfectly if there is only one form at a time. – Chintan Thummar May 23 '17 at 09:39
28

For information
if anyone use

$('#formId').submit();

Do not something like this

<button name = "submit">

It took many hours to find me that submit() won't work like this.

William Wu
  • 69
  • 7
A.Z. Soft
  • 526
  • 11
  • 12
  • 2
    Typo on key word `"sumit"` makes it unclear if the typo is unintented in answer, or was related to the problem. Do you mean that a button named `"submit"` messes up jquery form submit()? Or do you mean the problem was that you gave the button _name_ submit instead of the standard `type="submit"`? – Daryn Oct 09 '18 at 07:26
  • my intention was not to answer this question but to tell those who faced this problem. I think the problem is with button name without type defined, because I used onclick event to check some input before submit. If type=submit then form submit without my onclick event fire. – A.Z. Soft Oct 10 '18 at 01:42
  • ``` – Babak Asadzadeh Dec 08 '20 at 12:25
21

Use it to submit your form using jquery. Here is the link http://api.jquery.com/submit/

<form id="form" method="post" action="#">
    <input type="text" id="input">
    <input type="button" id="button" value="Submit">
</form>

<script type="text/javascript">
$(document).ready(function () {
    $( "#button" ).click(function() {
        $( "#form" ).submit();
    });
});
</script>
Chintan Thummar
  • 1,462
  • 19
  • 32
17

this will send a form with preloader :

var a=$('#yourform').serialize();
$.ajax({
    type:'post',
    url:'receiver url',
    data:a,
    beforeSend:function(){
        launchpreloader();
    },
    complete:function(){
        stopPreloader();
    },
    success:function(result){
         alert(result);
    }
});

i'have some trick to make a form data post reformed with random method http://www.jackart4.com/article.html

jacky
  • 171
  • 1
  • 2
16
$("form:first").submit();

See events/submit.

bluish
  • 26,356
  • 27
  • 122
  • 180
Ahmed Atia
  • 17,848
  • 25
  • 91
  • 133
15

Note that if you already installed a submit event listener for your form, the innner call to submit()

jQuery('#<form-id>').submit( function(e){ 
    e.preventDefault();
    // maybe some validation in here
    if ( <form-is-valid> ) jQuery('#<form-id>').submit();
});

won't work as it tries to install a new event listener for this form's submit event (which fails). So you have to acces the HTML Element itself (unwrap from jQquery) and call submit() on this element directly:

    jQuery('#<form-id>').submit( function(e){ 
      e.preventDefault();
      // note the [0] array access:
      if ( <form-is-valid> ) jQuery('#<form-id>')[0].submit();
    });
gutschilla
  • 157
  • 1
  • 4
10

You can also use the jquery form plugin to submit using ajax aswell:

http://malsup.com/jquery/form/

Richard
  • 21,728
  • 13
  • 62
  • 101
10

Note that in Internet Explorer there are issues with dynamically created forms. A form created like this will not submit in IE (9):

var form = $('<form method="post" action="/test/Delete/">' +
             '<input type="hidden" name="id" value="' + myid + '"></form>');
$(form).submit();

To get it working in IE create the form element and attach it before submitting like so:

var form = document.createElement("form");
$(form).attr("action", "/test/Delete")
       .attr("method", "post");
$(form).html('<input type="hidden" name="id" value="' + myid + '" />');
document.body.appendChild(form);
$(form).submit();
document.body.removeChild(form);

Creating the form like in example 1 and then attaching it will not work - in IE9 it throws a JScript error DOM Exception: HIERARCHY_REQUEST_ERR (3)

Props to Tommy W @ https://stackoverflow.com/a/6694054/694325

Community
  • 1
  • 1
Joel Peltonen
  • 13,025
  • 6
  • 64
  • 100
8

The solutions so far require you to know the ID of the form.

Use this code to submit the form without needing to know the ID:

function handleForm(field) {
    $(field).closest("form").submit();
}

For example if you were wanting to handle the click event for a button, you could use

$("#buttonID").click(function() {
    handleForm(this);    
});
Jesse
  • 8,605
  • 7
  • 47
  • 57
muzzamo
  • 1,721
  • 2
  • 14
  • 18
8

If the button is located between the form tags, I prefer this version:

$('.my-button').click(function (event) {
    var $target = $( event.target );
    $target.closest("form").submit();
});
Tk421
  • 6,196
  • 6
  • 38
  • 47
8
jQuery("a[id=atag]").click( function(){

    jQuery('#form-id').submit();      

            **OR**

    jQuery(this).parents("#form-id").submit();
});
Edwin de Koning
  • 14,209
  • 7
  • 56
  • 74
GKumar00
  • 81
  • 1
  • 3
6

My approach was slightly different, change the button into submit button and then click

$("#submit").click(function (event) {
  $(this).attr("type", "submit");
  $(this).click();
});
Naveen DA
  • 4,148
  • 4
  • 38
  • 57
5

IE trick for dynamic forms:

$('#someform').find('input,select,textarea').serialize();
daniel__
  • 11,633
  • 15
  • 64
  • 91
user2320873
  • 51
  • 1
  • 2
5

you could use it like this :

  $('#formId').submit();

OR

document.formName.submit();
Ram Ch. Bachkheti
  • 2,609
  • 2
  • 17
  • 14
3
function  form_submit(form_id,filename){
    $.post(filename,$("#"+form_id).serialize(), function(data){
        alert(data);
    });
}

It will post the form data on your given file name via AJAX.

Steve Nguyen
  • 5,854
  • 5
  • 21
  • 39
kdniazi
  • 39
  • 1
2

I recommend a generic solution so you don't have to add the code for every form. Use the jquery form plugin (http://jquery.malsup.com/form/) and add this code.

$(function(){
$('form.ajax_submit').submit(function() {
    $(this).ajaxSubmit();
            //validation and other stuff
        return false; 
});

});
johnlemon
  • 20,761
  • 42
  • 119
  • 178
2

you could do it like this :

$('#myform').bind('submit', function(){ ... });
vdegenne
  • 12,272
  • 14
  • 80
  • 106
-2

I have also used the following to submit a form (without actually submitting it) via Ajax:

  jQuery.get("process_form.php"+$("#form_id").serialize(), {}, 
    function() {
      alert("Okay!"); 
    });
brian newman
  • 3,964
  • 5
  • 25
  • 24