Javascript / jquery: create and publish virtual form

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

I could create an html form with the display: none, put the values ​​in this form and then run the invisible submit button. Is there a better way?

+6
source share
3 answers

The best way to do this outside of ajax is probably the way you describe with an invisible form. A strange problem.

0
source

If you do not want / cannot use Ajax, you need to do this using a form that will update your browser:

$('<form action="urlToServer" method="POST"></form>') .append('<input name="data" value="' + yourJSONData + '" />') .submit() ; 
+5
source

The "Claudio Bredfeldt" poster is on the right track to do this, but it omits the important information needed to complete this work.

Forms cannot be transmitted in all browsers unless they are attached to the DOM. So what you need to do is something more:

 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 does not appear on the user when you raise the post event of the form. You can also optionally β€œdelete” the form element after publishing so that the β€œreverse” event does not display correctly depending on the behavior of the browser.

+5
source

Source: https://habr.com/ru/post/945671/


All Articles