20 March 2019

This snippet creates html form and submits it, the same way as browser submits form "with redirect". If you need the redirect not an ajax solution, for example credit card payment.

Source code viewer
  1. function createAndPostHtmlForm(path, params) {
  2. var form = document.createElement('form');
  3. form.setAttribute('method', 'post');
  4. form.setAttribute('action', path);
  5.  
  6. for (var key in params) {
  7. if (params.hasOwnProperty(key)) {
  8. var hiddenField = document.createElement('input');
  9. hiddenField.setAttribute('type', 'hidden');
  10. hiddenField.setAttribute('name', key);
  11. hiddenField.setAttribute('value', params[key]);
  12.  
  13. form.appendChild(hiddenField);
  14. }
  15. }
  16.  
  17. document.body.appendChild(form);
  18. form.submit();
  19. },
  20.  
  21. /* Usage: */
  22. createAndPostHtmlForm('https://example.com/submit.php', {
  23. field1: 'value1',
  24. field2: 'value2'
  25. });
Programming Language: Javascript