Reputation: 1513
I have two input fields and I want to post the same data to two different php files, depending on whatever button is clicked.
In my case the data is going into foo.php
only, but not into excel.php
.
I want the data to go to excel.php, if second button is pressed.
JS:
$(function() {
$("#from").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function(selectedDate) {
$("#to").datepicker("option", "minDate", selectedDate);
}
});
$("#to").datepicker({
defaultDate: "+1w",
changeMonth: true,
numberOfMonths: 3,
onClose: function(selectedDate) {
$("#from").datepicker("option", "maxDate", selectedDate);
}
});
});
HTML:
<form action="foo.php" method="post">
<label for="from">From</label>
<input type="text" id="from" name="from" />
<label for="to">to</label>
<input type="text" id="to" name="to" /> <br>
<input type="submit" value="Viewchart">
</form>
<form action="excel.php" method="post">
<input type="submit" value="Download Excel file">
</form>
Upvotes: 10
Views: 1170
Reputation: 7862
You can change the action
attribute when the button is clicked as follow:
$(function() {
$( ".actionable" ).click( function() {
$('#myForm').attr('action', $(this).data("action"));
$('#myForm').submit();
});
});
And set the next data-*
attributes to your buttons:
<form name="form" id="myForm" method="post">
<input type="submit" class="actionable" value="Viewchart" data-action="foo.php"/>
<input type="submit" class="actionable" value="Excel" data-action="excel.php"/>
</form>
You can see how it works here.
data-*
attributes here: http://www.w3schools.com/tags/att_global_data.aspClarification for OP:
The
$( function() {} );
block —equivalent to$(document).ready( function() {} );
— specify a function to execute when the DOM is fully loaded; you should put inside all your code which interact with the elements of the DOM.
Upvotes: 10
Reputation: 701
It can be done in your way by next script and little change in second form declaration
for second form you should set id:
<form id="form2" action="excel.php" method="post">
And you should add the next script:
$("#form2").submit( function(eventObj){
$(this).append('<input type="hidden" name="from" value="'+$("#from").val()+'" /> ');
$(this).append('<input type="hidden" name="to" value="'+$("#to").val()+'" /> ');
return true;
});
Upvotes: 2
Reputation: 37
That happens because you have one form with action="foo.php". It doesn't matter which button you click it will always send the data to the action of the form in this case "foo.php".
Solution:
Seperate the inputs into two forms and set the action of the second form to "excel.php". Then it should work. Hope it helped you.
Edit: Saw the second form in the last second. In this case you just have to take the input of "to" or "from" down to the second form.
Upvotes: -2