window.open to pass parameters to php and trigger pdf creation and view

非 Y 不嫁゛ 提交于 2019-12-06 09:52:41
Ivan Hušnjak

There is a solution to send POST data with window.open() and it is quite simple: Window.open and pass parameters by post method

It can even be made without any actual HTML code involved just with pure javascript programming.

// Edit: added javascript only solution:

<input type="button" value="Open" onclick="openWindow();" />
<script>
function openWindow(){
    // create <form>
    var form = document.createElement('form');
    form.method = 'POST';
    form.action = 'process.php';
    form.target = 'window_1'; // target the window
    // append it to body
    var body = document.getElementsByTagName('body')[0];
    body.appendChild(form);
    // create an element
    var child1 = document.createElement('input');
    child1.type = 'text'; // or 'hidden' it is the same
    child1.name = 'elem1';
    child1.value = 'some value';
    // append it to form
    form.appendChild(child1);
    // create another element
    var child2 = document.createElement('input');
    child2.type = 'text'; // or 'hidden' it is the same
    child2.name = 'elem2';
    child2.value = 'some other value';
    // append it to form
    form.appendChild(child2);

    // create window
    window.open('', 'window_1');

    // submit form
    form.submit();
    body.removeChild(form); // clean up
}
</script>
Ignacio Vazquez-Abrams

window.open() can only perform GET requests. You will need to create a form with the appropriate controls and target if you want to have the same effect with POST instead.

You could create a <form> with hidden inputs and use JavaScript to submit the form. Notice the target="_blank" attribute which causes the form to post to a new window.

<a href="#" onclick="document.forms['pdfForm'].submit();return false;">Generate PDF</a>

<form target="_blank" id="pdfForm" name="pdfForm" method="POST">
    <input type="hidden" name="param1" value="val1" />
    <input type="hidden" name="param2" value="val2" />
</form>
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!