Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Distinguish among submit buttons on HTML form with two submit buttons [duplicate]

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...

like image 486
Mike Janssens Avatar asked Jul 03 '15 05:07

Mike Janssens


1 Answers

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
} ?>
like image 103
webketje Avatar answered Sep 21 '22 01:09

webketje