Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript / jquery: create and post virtual form [closed]

In javascript, I have some data that I want send as a post (NOT ajax). It should act the same as if the user had clicked a submit button. However, I do not have an actual form. The data is collected from the page into various variables, including an array that I encode as json.

I could create an html form with display:none, place the values into this form, and then trigger the invisible submit button. Is there a better way?

like image 858
user984003 Avatar asked May 23 '13 10:05

user984003


2 Answers

If you don't want/can't use Ajax, then you have to do it with a form, which is going to refresh your browser:

 $('<form action="urlToServer" method="POST"></form>')
    .append('<input name="data" value="' + yourJSONData + '" />')
    .submit()
;
like image 160
Claudio Bredfeldt Avatar answered Sep 18 '22 00:09

Claudio Bredfeldt


Poster "Claudio Bredfeldt" is on the right track to do this, but he omits some crucial information necessary to make this work.

Forms cannot submit across all browsers unless they are attached to the DOM. So what you need to do is something more like this:

var $form = $('<form action="http://myurl" method="POST">');
$form.append('<input name="name" value="bob" />');
$form.appendTo($('body')).submit();

Optionally you may want to attach some css to the form so that it doesn't appear to the user when you cause the form post event to occur. You also may optionally want to "remove" the form element after posting so that a "back" event will not mis-display depending on browser cache behavior.

like image 26
kamelkev Avatar answered Sep 20 '22 00:09

kamelkev