fish_ball fish_ball - 5 months ago 4x
Javascript Question

Simulate post form submit with a function call with javascript

With Jquery, we can simulate to submit a form:

<form id="form1" method="post">
<input name="key1" value="value1" />
<input name="key2" value="value2" />

With a ajax function call:

$.post('', { key1: 'value1', key2: 'value2' }, function() {
// do call back

If we use

success: function() {
// do call back

Ok, now comes my question:

Now I don't have the form in the markup.

And I want to submit a form with some dynamic content with post method.

I want to make a function call to simulate the procedure, maybe something like:'/url', {key1: 'value1', key2: 'value2'});

After that call, the effect is just the same with that I have the form above and I submit it, with a natural synchronize way.

Is there a nice way to do this?

If the problem is not clear, I can make an ugly example to explain what I want: = function(url, fields) {
var $form = $('<form action="'+url+'" method="post"></form>');
var key, val;
for(key in fields) {
if(fields.hasOwnProperty(key)) {
val = fields[key];
$form.append('<input type="hidden" name="'+key+'" value="'+val+'" />');

The above method can do, but I think it is not nice enough, and when the fields has some special character or something else it may cause error.

So I'm trying to find out if there is a good way to make it when you encounter the same problem.


You can use jQuery to construct the form functionally, rather than by concatenating strings, so special characters won't be a problem.

var util = {}; = function(url, fields) {
    var $form = $('<form>', {
        action: url,
        method: 'post'
    $.each(fields, function(key, val) {
             type: "hidden",
             name: key,
             value: val