How can I simulate a form submit via POST in JavaScript?

I need a cross-browser method in JavaScript to navigate to a new page via a POST request without using Ajax. How can I accomplish this?

function submitPostForm(targetUrl, dataObj) {
  var newForm = document.createElement('form');
  newForm.method = 'POST';
  newForm.action = targetUrl;
  for (var prop in dataObj) {
    if (dataObj.hasOwnProperty(prop)) {
      var hiddenField = document.createElement('input');
      hiddenField.type = 'hidden';
      hiddenField.name = prop;
      hiddenField.value = dataObj[prop];
      newForm.appendChild(hiddenField);
    }
  }
  document.body.appendChild(newForm);
  newForm.submit();
}

hey, u could also use a hidden iframe to handle the post call. works in most browers and keeps your main page untouched.

The solution of dynamically creating a form and submitting it is reliable and straightforward for cases where you need to perform a POST without relying on Ajax. In my experience, it’s particularly effective when working with APIs that require form submission semantics or when dealing with legacy code. I made sure that each hidden input is properly created to avoid data integrity issues. This technique reduces the need for additional libraries and keeps the implementation clean while ensuring cross-browser compatibility.