Advertisement
Advertisement


Submit a form using jQuery


Question

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

2019/09/24
1
481
9/24/2019 8:59:00 PM


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.

2014/01/07

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'];
2017/04/27

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()
2015/07/24

From the manual: jQuery Doc

$("form:first").submit();
2020/02/18

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.

2019/05/16

Source: https://stackoverflow.com/questions/1200266
Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Email: [email protected]