CL So
CL So

Reputation: 3759

How to create non-ajax post request in javascript?

Now I do that in this way.

var form=document.createElement('form');
form.setAttribute('method', 'get');
form.setAttribute('action', 'url');
hidden=document.createElement('input');
hidden.setAttribute('type', 'hidden');
hidden.setAttribute('name', 'name');
hidden.setAttribute('value', 'value');
form.appendChild(hidden);
form.submit();

But I want save the cost on creating the DOMs

Is it possible to submit post request in javascript without DOM?

Upvotes: 4

Views: 2297

Answers (2)

Thomas Junk
Thomas Junk

Reputation: 5676

Yes.

document.forms[0].submit()

submits the 1st form on the page. And it is the typical way to submit a form in a "non-ajax" way. But the term "non ajax" is misleading in your question, hence the "POST"-verb is a simple http-verb. And there is no difference in using it "ajax"-way or a "non-ajax" way. The artificial difference one could make is: "application/x-www.formurlencoded" is the preferred format of the browser or "application/json" as you are doing it with "ajax".

P.S.: It is hard to answer your question. Of course you could avoid the dynamic creation of a form-element; but you have to use a form element anyways to do a non-ajaxy submit.

Upvotes: 3

Lee Avital
Lee Avital

Reputation: 542

I believe you won't actually take much a performance hit doing it the way you are. The big issues with editing the DOM is actually adding to the document as it requires re-rendering and stuff.

Upvotes: 1

Related Questions