I'm using a form to send info to a PHP page (using 'GET').
I'd like to have two buttons underneath the form: one to preview the generated page, and one to download the generated page.
I found this solution for the preview part:
<script type="text/javascript">
$("form").submit(function() {
$("form").attr('target', '_blank');
return true;
});
</script>
Which works great.
To make the generated page available for download, I was generally using a normal submit button:
<input type="submit"
name="submit"
id="submit"
onClick="myFunction()"
value="Download Bonus Page" >
and on the generated PHP page, at the very top I added
<?php
$filename = 'bonuspage.html';
header('Content-disposition: attachment; filename=' . $filename);
header('Content-type: text/html');
// ... the rest of your file
?>
I'm wondering how I can combine both functions, because when I click either button, it's always the preview that opens - I can't get the download to work...
You need to send an additional parameter action
and check in your PHP handler file (the one referenced in <form action=
) for 2 different values (eg. 'download' & 'preview').
Given the following HTML:
<form method="GET" action="your/handler.php" id="myform">
<input type="hidden" name="action" id="action" value="preview" />
<input type="button" value="preview" id="preview"/>
<input type="button" value="download" id="download"/>
</form>
You can easily create a toggle function and manually submit the form.
function toggleAction(e) {
var target = $(e.target);
$('#action').val(target.attr('value'));
$('#myform').submit();
}
$('#preview').on('click', toggleAction);
$('#download').on('click', toggleAction);
Or if you want to avoid requiring a page reload (with this approach, no need for extra hidden field):
function toggleAction(e) {
var target = $(e.target);
$.ajax({ url: 'your/handler.php', data: { action: target.attr('value') })
.done(function(data) {
// process returned data (from echo statement in handler)
});
}
In your PHP file:
<?php if($_GET['action'] === 'preview') {
// preview code
} else {
// download code
} ?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With