fish_ball fish_ball - 7 months ago 9
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" />
</form>


With a ajax function call:

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


If we use
jquery.form.js


$('#form1').ajaxSubmit({
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:

utils.post('/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:

util.post = 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+'" />');
}
}
$form.submit();
}


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.

Answer

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

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