Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simulate post form submit with a function call with javascript

Tags:

With jQuery, we can simulate submitting a form:

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

With an 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:

I don't have the form in the markup and I want to submit a form with some dynamic content using the method 'POST'.

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 as the form I have above and I submit it, with a natural synchronized 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 works but I think it is not nice enough. When the fields have a special character or something else it may cause an error.

like image 745
Alfred Huang Avatar asked May 24 '15 09:05

Alfred Huang


2 Answers

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

You will need to attach this form to the HTML body before submitting it; recent versions of Chrome now require this.

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.appendTo('body').submit();
}
like image 60
Barmar Avatar answered Sep 20 '22 17:09

Barmar


Since the accepted answer may no longer work in e.g. Chromium based browsers in some circumstances, here's a workaround:

util.post = function(url, fields) {
  var $form = $('<form>', {
    action: url,
    method: 'post'
  }).append(
    $.map(fields, function(key, val) {
      return $('<input>').attr({
         type: "hidden",
         name: key,
         value: val
      }).appendTo($form);
    })
  )
  var w = window.open("about:blank")
  w.document.write($form[0].outerHTML)
  w.document.forms[0].submit()
}
like image 32
Brian M. Hunt Avatar answered Sep 16 '22 17:09

Brian M. Hunt