How to submit a form in a POST request using JavaScript
I was working on a Django project a couple of days ago where I needed to use JavaScript to submit a form in a POST request. The response of this request is a PDF file generated with ReportLab. I wanted the browser to prompt the user to download the file or open it in the browser in another window.
I was trying to do this with AJAX at first, but apparently you’re not really supposed to do downloads within an AJAX call (I’m a complete JavaScript newbie). It would return the actual content of the file as if you opened it with a text editor. I’ve found ‘tricks’ online to make the browser open the file in the proper format, like this example below:
generateReportPdf: function(url) { var exportForm = $('form#export-form'); $.ajax({ url: url, type: 'POST', data: exportForm.serialize(), success: function(data) { window.open('data:application/pdf,' + escape(data)); } }); }
But this won’t work with all browsers. It works with Firefox but probably won’t work with Internet Explorer, so this is not really a good solution.
I ended up just having to do a regular form submission instead. I found this example below on StackOverflow and works quite well:
function post_to_url(path, params, method) { method = method || 'POST'; var form = document.createElement('form'); // Move the submit function to another variable // so that it doesn't get overwritten. form._submit_function_ = form.submit; form.setAttribute('method', method); form.setAttribute('action', path); form.setAttribute('target', '_blank'); for(var key in params) { var hiddenField = document.createElement('input'); hiddenField.setAttribute('type', 'hidden'); hiddenField.setAttribute('name', key); hiddenField.setAttribute('value', params[key]); form.appendChild(hiddenField); } document.body.appendChild(form); form._submit_function_(); // Call the renamed function. }
Tags: tech, software development, javascript