96

Is there a way in jQuery to create and submit a form on the fly?

Something like below:

<html>
    <head>
        <title>Title Text Goes Here</title>
        <script src="http://code.jquery.com/jquery-1.7.js"></script>
        <script>
            $(document).ready(function(){alert('hi')});
            $('<form/>').attr('action','form2.html').submit();
        </script>
    </head>
    <body>
        Content Area
    </body>
</html>

Is this supposed to work or there is a different way to do this?

Max Base
  • 639
  • 1
  • 7
  • 15
Santosh Gokak
  • 3,393
  • 3
  • 22
  • 24

12 Answers12

118

There were two things wrong with your code. The first one is that you included the $(document).ready(); but didn't wrap the jQuery object that's creating the element with it.

The second was the method you were using. jQuery will create any element when the selector (or where you would usually put the selector) is replaced with the element you wish to create. Then you just append it to the body and submit it.

$(document).ready(function(){
    $('<form action="form2.html"></form>').appendTo('body').submit();
});

Here's the code in action. In this example, it doesn't auto submit, just to prove that it would add the form element.

Here's the code with auto submit. It works out fine. Jsfiddle takes you to a 404 page because "form2.html" doesn't exist on its server, obviously.

Purag
  • 16,941
  • 4
  • 54
  • 75
  • the first issue you mentioned though is not an issue :) – Santosh Gokak Nov 04 '11 at 00:15
  • 2
    @user42540: Not necessarily, but it's better to fire your JS code when the page has completed loading. This will prevent unwanted errors. – Purag Nov 04 '11 at 00:48
  • 3
    It may work on some browsers, but there is a good reason to include most DOM manipulation code inside a `$(document).ready()` block - it ensures that the browser is able to safely make any changes to the DOM. Otherwise, picky browsers like IE6/7 spit the dummy if you try to change anything before the whole page has loaded. – GregL Nov 04 '11 at 00:50
106

Yes, it is possible. One of the solutions is below (jsfiddle as a proof).

HTML:

<a id="fire" href="#" title="submit form">Submit form</a>

(see, above there is no form)

JavaScript:

jQuery('#fire').click(function(event){
    event.preventDefault();
    var newForm = jQuery('<form>', {
        'action': 'http://www.google.com/search',
        'target': '_top'
    }).append(jQuery('<input>', {
        'name': 'q',
        'value': 'stack overflow',
        'type': 'hidden'
    }));
    newForm.submit();
});

The above example shows you how to create form, how to add inputs and how to submit. Sometimes display of the result is forbidden by X-Frame-Options, so I have set target to _top, which replaces the main window's content. Alternatively if you set _blank, it can show within new window / tab.

Tadeck
  • 132,510
  • 28
  • 152
  • 198
  • Good solution (albeit a bit long), but the input didn't show up. – Purag Nov 03 '11 at 23:27
  • @Purmou: The actual solution is the form creation and then `submit()` call. I intentionally provided long form creation code to show how to create the form and its elements. I believe this is quite ok. – Tadeck Nov 03 '11 at 23:30
  • @Tradeck: Heh, I didn't read your Javascript properly. The input is filled up automatically right before the form is submitted. Well done. – Purag Nov 03 '11 at 23:30
  • 23
    .appendTo('body') is needed for it to work in my Firefox (23.0.1). Otherwise it just returns a form object but does not submit. – Curtis Yallop Sep 06 '13 at 23:23
  • @CurtisYallop: That is possible, sometimes the form needs to be entered into the DOM before submission. I will need to confirm that, though. Could you check in the meantime, if it properly handles submissions of invisible forms? – Tadeck Sep 06 '13 at 23:53
  • 6
    newForm.hide().appendTo("body").submit(); // doesnt display the fields and works in FF – laffuste Nov 14 '13 at 04:39
  • @CurtisYallop same goes for IE11. – HischT Oct 02 '15 at 09:35
  • 5
    As is this does a GET and is akin to tacking on a query string to the target URI. Would assume many people are wanting to use a form to POST. In case it is not obvious, use `'method': post` to accomplish that. – ficuscr Nov 11 '15 at 21:11
  • newForm.appendTo('body').submit(); is required for IE too – Tejasvi Hegde Mar 31 '16 at 09:11
  • @tadeck How to send multiple params ? – iit2011081 Nov 25 '16 at 05:43
49

Its My version without jQuery, simple function can be used on fly

Function:

function post_to_url(path, params, method) {
    method = method || "post";

    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", path);

    for(var key in params) {
        if(params.hasOwnProperty(key)) {
            var hiddenField = document.createElement("input");
            hiddenField.setAttribute("type", "hidden");
            hiddenField.setAttribute("name", key);
            hiddenField.setAttribute("value", params[key]);

            form.appendChild(hiddenField);
         }
    }

    document.body.appendChild(form);
    form.submit();
}

Usage:

post_to_url('fullurlpath', {
    field1:'value1',
    field2:'value2'
}, 'post');
Muthukumar Anbalagan
  • 1,138
  • 12
  • 15
14

Like Purmou, but removing the form when submit will done.

$(function() {
   $('<form action="form2.html"></form>').appendTo('body').submit().remove();
});
javray
  • 141
  • 1
  • 3
13

Josepmra example works well for what i need. But i had to add the line form.appendTo(document.body) for it to work.

var form = $(document.createElement('form'));
$(form).attr("action", "reserves.php");
$(form).attr("method", "POST");

var input = $("<input>")
    .attr("type", "hidden")
    .attr("name", "mydata")
    .val("bla" );

$(form).append($(input));

form.appendTo(document.body)

$(form).submit();
Max Base
  • 639
  • 1
  • 7
  • 15
webs
  • 528
  • 5
  • 11
9

Yes, you just forgot the quotes ...

$('<form/>').attr('action','form2.html').submit();
Nicolas Thery
  • 2,319
  • 4
  • 26
  • 36
6

Try with this code, It is a totally dynamic solution:

var form = $(document.createElement('form'));
$(form).attr("action", "reserves.php");
$(form).attr("method", "POST");

var input = $("<input>").attr("type", "hidden")
                        .attr("name", "mydata")
                        .val("bla");
$(form).append($(input));
$(form).submit();
Max Base
  • 639
  • 1
  • 7
  • 15
josepmra
  • 617
  • 9
  • 25
2

Why don't you $.post or $.get directly?

GET requests:

$.get(url, data, callback);

POST requests:

$.post(url, data, callback);

Then you don't need a form, just send the data in your data object.

$.post("form2.html", {myField: "some value"}, function(){
  alert("done!");
});
SparK
  • 5,181
  • 2
  • 23
  • 32
  • 1
    Because need to trigger download from the server and with post/get it's not working. – a20 May 24 '16 at 10:34
  • Also with this you don't leave the page. – robsch Jan 04 '17 at 09:32
  • @a20 What lacks there is a server-side header `Content-Disposition: Attachment;` to force download. – SparK Jan 04 '17 at 20:56
  • @SparK hmmmm .. your comment makes me wonder, isn't there any mime-type on server side that browsers can interpret (or not interpret and force) download. For example a zip file. Is it not possible in any way to specify that it's in response to a user's download request so trigger download ... – a20 Jan 05 '17 at 01:12
  • @a20 Yes, `Content-Type: application/octet-stream;`. There's also the `download` attribute in anchors... client-side thing (https://davidwalsh.name/download-attribute) – SparK Jan 05 '17 at 16:23
2

Using Jquery

$('<form/>', { action: url, method: 'POST' }).append(
    $('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
    $('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
).appendTo('body').submit();
Jairus
  • 816
  • 8
  • 27
1

Steps to take:

  1. First you need to create the form element.
  2. With the form you have to pass the URL to which you wants to navigate.
  3. Specify the method type for the form.
  4. Add the form body.
  5. Finally call the submit() method on the form.

Code:

var Form = document.createElement("form");
Form.action = '/DashboardModule/DevicesInfo/RedirectToView?TerminalId='+marker.data;
Form.method = "post";
var formToSubmit = document.body.appendChild(Form);
formToSubmit.submit();
trincot
  • 317,000
  • 35
  • 244
  • 286
0

Assuming you want create a form with some parameters and make a POST call

var param1 = 10;

$('<form action="./your_target.html" method="POST">' +
'<input type="hidden" name="param" value="' + param + '" />' +
'</form>').appendTo('body').submit();

You could also do it all on one line if you so wish :-)

Anthony
  • 575
  • 6
  • 8
0

You can use this function in form on submit.

But this is in javascript, I would like change this to jquery.

I searched online but none retains the DOM, so it can be removed after submit.

const trimTypes = ['email', 'hidden', 'number', 'password', 'tel', 'text', null, ''];

function submitTrimmedDataForm(event) {
    event.preventDefault();

    let currentForm = event.target;
    var form = document.createElement("form");
    form.style.display = "none";
    form.method = currentForm.getAttribute('method');
    form.action = currentForm.getAttribute('action');

    Array.from(currentForm.getElementsByTagName('input')).forEach(el => {
        console.log("name :" + el.getAttribute('name') + ", value :" + el.value + ", type :" + el.getAttribute('type'));
        var element = document.createElement("input");
        let type = el.getAttribute('type');
        if (trimTypes.includes(type)) {
            element.value = trim(el.value);
        }
        element.name = el.getAttribute('name');
        element.type = el.getAttribute('type');
        form.appendChild(element);
    });

    Array.from(currentForm.getElementsByTagName('select')).forEach(el => {
        console.log("select name :" + el.getAttribute('name') + ", value :" + el.value);
        var element = document.createElement("input");
        element.value = el.value;
        element.name = el.getAttribute('name');
        element.type = 'text';
        form.appendChild(element);
    });

    document.body.appendChild(form);
    form.submit();
    document.body.removeChild(form); // this is important as well
}
Max Base
  • 639
  • 1
  • 7
  • 15
Aditya Yada
  • 168
  • 1
  • 2
  • 9