How to Make a Post Request in JavaScript Without Using a Form

From WikiHTP

To make a request of type POST to change the page in the navigator, the logic wants that one uses a form with a button on which one would click. It is possible in JavaScript to make a POST request without having to use a form conventionally.

Using JavaScript Method[edit]

For that, one can create a function which would take in parameter the destination URL and the names and values ​of the parameters.

This function will first create a form dynamically, using the methods provided for the management of the DOM and especially the createElement() method. The setAttribute() method will set the destination URL and the POST method will serve as the method of submitting information. Then, for each parameter, we will create a <input> element of hidden type, and we will give it the names and values ​​corresponding to the parameters. To avoid a possible problem, check that the parameter has a value with the hasOwnProperty() method.

We will add these fields to the form, then add this form to the web page to avoid compatibility issues with other browsers. All you have to do is submit this form with the submit() method and you get a POST redirection method in JavaScript:

function post_en_url (url, parameters) {
    // Dynamic creation of the form
    var form = document.createElement(form);
    form.setAttribute(method, POST);
    form.setAttribute(action, url);
    // Add parameters as hidden fields
    for (var key in parameters) {
       if (parametres.hasOwnProperty (key)) {
         var fieldCache = document.createElement(input);
         fieldCache.setAttribute(type, hidden);
         fieldCache.setAttribute(name, key);
         fieldCache.setAttribute(value, parameters [key]);
   // Add the form to the page and submit the form

About This Tutorial

This page was last edited on 28 January 2019, at 06:35.