Home >Web Front-end >JS Tutorial >How Can I Submit POST Requests in JavaScript Using a Form?

How Can I Submit POST Requests in JavaScript Using a Form?

Barbara Streisand
Barbara StreisandOriginal
2024-12-28 07:34:28848browse

How Can I Submit POST Requests in JavaScript Using a Form?

Submitting POST Requests in JavaScript: A Form-Based Approach

To submit POST requests in JavaScript and navigate to a different page as if submitting a form, consider this solution:

/**
 * 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') {
  // Create a form and add it to the DOM
  const form = document.createElement('form');
  form.method = method;
  form.action = path;
  document.body.appendChild(form);

  // Create hidden input fields for each parameter
  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);
    }
  }

  // Submit the form
  form.submit();

  // Optionally, remove the form from the DOM
  document.body.removeChild(form);
}

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

The above is the detailed content of How Can I Submit POST Requests in JavaScript Using a Form?. 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