I am building a pizza ordering form that calculates form fields depends on user choices and returns the total. The first input will be the currency drop down, once user selects currency, it should pass value to PHP variable $currency (so that it will calculate the exchange rate) without the need to submit the form of course.
I have seen a lot of similar codes, but got confused, I know I should be using JavaScript / Ajax, but my knowledge is weak in that.
Can you please paste a simple code that will pass the $currency value to PHP?
<html>
<head>
<title></title>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js" type="text/javascript"></script>
<script type="text/javascript">
jQuery(function($){
$("#currency").change(function(){
var selected_value = $(this).val();
/*AJAX CODE HERE TO PASS VALUE OF DROP DOWN TO PHP*/
$.post("CurrencyCalculator.php", $("#currency").serialize()); //this is the problematic part: it needs to pass the $currency variable
})
})
</script>
</head>
<body>
Select any one:
<select id="currency" name="currency" onchange="selectDropdown()">
<option value="EUR" >Euro</option>
<option value="USD" >US Dollar</option>
<option value="GBP" >British Pound</option>
</select>
</body>
</html>
Php is run on the server before the HTML is returned to the browser. You cannot pass a value from an html form to a php variable for this reason.
You can, however, submit a form to a php page for processing.
<form action="myPhpPage.php">
Then inside of myPhpPage.php you can use $_GET['variableName'] to retrieve the value
Since its a drop down menu where the currency is selected, give the menu an onchange
attribute and send the info to your PHP file to process it.
Try looking into $_POST and $_GET
<?php
if(($_POST['submit']))
{
// do your stuff
}
?>
<form action="something" method="post">
<input type="submit" name="submit" value="Vote!">
</form>
when this form is pressed, the phpp code will be run