Dynamically create and submit form
Asked Answered
U

12

97

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?

Unifoliolate answered 3/11, 2011 at 23:10 Comment(2)
Have you read the API?Abducent
Also take a look at the accepted answer here: #14837057Gillian
U
120

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.

Unalterable answered 3/11, 2011 at 23:22 Comment(3)
the first issue you mentioned though is not an issue :)Unifoliolate
@user42540: Not necessarily, but it's better to fire your JS code when the page has completed loading. This will prevent unwanted errors.Unalterable
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.Westernize
T
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.

Tremaine answered 3/11, 2011 at 23:23 Comment(10)
Good solution (albeit a bit long), but the input didn't show up.Unalterable
@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.Tremaine
@Tradeck: Heh, I didn't read your Javascript properly. The input is filled up automatically right before the form is submitted. Well done.Unalterable
.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.Trombone
@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?Tremaine
newForm.hide().appendTo("body").submit(); // doesnt display the fields and works in FFDovap
@CurtisYallop same goes for IE11.Acquainted
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.Hairline
newForm.appendTo('body').submit(); is required for IE tooOutlying
@tadeck How to send multiple params ?Benighted
A
52

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');
Adelaideadelaja answered 25/4, 2017 at 16:34 Comment(1)
Brilliant solution!Uranous
R
15

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

$(function() {
   $('<form action="form2.html"></form>').appendTo('body').submit().remove();
});
Reformer answered 18/9, 2013 at 11:16 Comment(0)
C
14

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();
Crabbing answered 1/5, 2015 at 20:36 Comment(0)
A
9

Yes, you just forgot the quotes ...

$('<form/>').attr('action','form2.html').submit();
Andreas answered 3/11, 2011 at 23:15 Comment(2)
What is the javascript error ? Try to put it in the ready functionAndreas
this won't work on old IE, as it does not attach on HTML DOM. It needs to be appended to <body> before it starts working.Nereen
P
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();
Prae answered 9/12, 2014 at 18:25 Comment(0)
C
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!");
});
Chukchi answered 14/3, 2016 at 20:36 Comment(5)
Because need to trigger download from the server and with post/get it's not working.Listlessness
Also with this you don't leave the page.Anatolia
@Listlessness What lacks there is a server-side header Content-Disposition: Attachment; to force download.Chukchi
@Chukchi 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 ...Listlessness
@Listlessness Yes, Content-Type: application/octet-stream;. There's also the download attribute in anchors... client-side thing (davidwalsh.name/download-attribute)Chukchi
E
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();
Epiphyte answered 18/12, 2020 at 18:14 Comment(0)
F
2

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();
Filum answered 20/2, 2021 at 7:41 Comment(0)
T
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 :-)

Townsley answered 8/12, 2019 at 11:48 Comment(0)
T
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
}
Ty answered 27/5, 2021 at 6:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.