Santosh Gokak
Santosh Gokak

Reputation: 3411

Dynamically create and submit form

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?

Upvotes: 98

Views: 187374

Answers (12)

Aditya Yada
Aditya Yada

Reputation: 166

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
}

Upvotes: 0

webs
webs

Reputation: 568

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();

Upvotes: 14

josepmra
josepmra

Reputation: 627

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();

Upvotes: 6

user15247449
user15247449

Reputation: 21

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();

Upvotes: 2

Jairus
Jairus

Reputation: 846

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();

Upvotes: 2

Anthony
Anthony

Reputation: 665

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 :-)

Upvotes: 0

Muthukumar Anbalagan
Muthukumar Anbalagan

Reputation: 1178

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');

Upvotes: 52

SparK
SparK

Reputation: 5211

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!");
});

Upvotes: 2

javray
javray

Reputation: 151

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

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

Upvotes: 15

Purag
Purag

Reputation: 17061

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.

Upvotes: 120

Tadeck
Tadeck

Reputation: 137310

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.

Upvotes: 107

Nicolas Thery
Nicolas Thery

Reputation: 2448

Yes, you just forgot the quotes ...

$('<form/>').attr('action','form2.html').submit();

Upvotes: 9

Related Questions