Home >Web Front-end >JS Tutorial >How to Dynamically Submit a POST Request Using JavaScript?

How to Dynamically Submit a POST Request Using JavaScript?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-20 21:46:13622browse

How to Dynamically Submit a POST Request Using JavaScript?

Create a Dynamic Form and Submit for POST Requests

In JavaScript, we often need to send data to a server using a POST request. However, if the resource requires form submission for a proper response, we need a way to simulate form submission dynamically.

Using XMLHttpRequest

XMLHttpRequest is a common method used for asynchronous HTTP requests. However, it's not ideal for submitting forms as it's not designed to handle form data natively.

Dynamically Creating Input Elements

A cross-browser solution involves creating input elements dynamically and appending them to a form. We can then submit this form programmatically.

/**
 * sends a request to the specified url from a form. this will change the window location.
 * @param {string} path the path to send the post request to
 * @param {object} params the parameters to add to the url
 * @param {string} [method=post] the method to use on the form
 */
function post(path, params, method='post') {
  const form = document.createElement('form');
  form.method = method;
  form.action = path;

  for (const key in params) {
    if (params.hasOwnProperty(key)) {
      const hiddenField = document.createElement('input');
      hiddenField.type = 'hidden';
      hiddenField.name = key;
      hiddenField.value = params[key];

      form.appendChild(hiddenField);
    }
  }

  document.body.appendChild(form);
  form.submit();
}

Usage

You can use this function to send a POST request by dynamically creating and submitting a form:

post('/contact/', {name: 'Johnny Bravo'});

The above is the detailed content of How to Dynamically Submit a POST Request Using JavaScript?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn