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
Related
All of the examples of making drop-down forms that I can find involve having a separate PHP file. I'm trying to embed some code into a Weebly page, so I'm not sure that I can save a separate PHP file on the server. So is it possible to avoid PHP entirely? Maybe do everything in JavaScript and jQuery? Or to put the form and the PHP in the same HTML file?
More specifically what I'm trying to do is make a page where there are several drop-down forms. The user selects several options, clicks submit, the client-side back-end does some computation on the inputs, and prints out a result.
I've been trying to follow this guide for dropdowns: https://www.w3schools.com/tags/tag_select.asp
And I've been following this for using PHP in forms: https://www.ntchosting.com/encyclopedia/scripting-and-programming/php/php-in/
With that guidance I created this non-working code:
<!DOCTYPE html>
<?php
$Level = $_POST["level"];
?>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
</head>
<body>
<form action="<?php echo $PHP_SELF;?>" method="post">
Choose a level: <select name="level" id="level">
<option value="high">High</option>
<option value="med">Medium</option>
<option value="low">Low</option>
</select>
</form>
<p>
<?php
echo "".$Level;
?>
</p>
</body>
</html>
I say that it's not working because when I click on anything in the drop-down, nothing happens.
This further information came from an exchange in the comments:
Ah, this really doesn't need to interact with the server. It's ultimately just going to be a tool so that customers can get an automatically generated estimated quote on a price. So they answer some questions (i.e. select some drop-downs and enter some numbers in fields) and click submit, and the web page spits out an estimate. No information saved or anything like that, so it should be fine to handle everything client-side. From your description, though, it sounds like that can't be done with PHP then. I don't think Weebly will let me change the file extension.
You certainly can. You can use the onSubmit attribute on your form to run some javascript (and by extension jquery) without actually submitting the form. More specifically, it would look something like this:
<form onSubmit="return yourJavascriptFunction()" method="post">
Inside your script, you can get the dropdown values from the form's fields using document.getElementById(yourDropdownID) and perform any necessary actions. If you don't want your form to redirect, just return false; on your function. Using this method, you don't really need a form, and can use some <select> tags with id, as well as a pseudo submit button:
<button onclick="yourFunction()">Submit</button>
if you want to do this with php you have to change the extension as php and add a submit button otherwise you can do this without php easly like below.
<form action="#" method="post">
Choose a level: <select name="level" id="level" onChange="document.getElementById('selectedValue').innerHTML = this.value;">
<option value="high">High</option>
<option value="med">Medium</option>
<option value="low">Low</option>
</select>
</form>
<p> <span id="selectedValue"></span></p>
remove the DOCTYPE html and change the extension of your file to .php
I am working off a snippet of someone else's code I have found. I would like to update a PHP variable once the select field has changed.
The name of the of the variable is $ProductType as below. The current code does what is expected so now all I'd like to do is set the variable equal to the changed option
<?php
$ProductType = '';
if(isset($_GET['trade'])){
//Everything in here will get echoed in the DIV
echo "You selected: ".$_GET['trade'];
$ProductType = $_GET['trade']; // I'd have thought this might work but when I echo $ProductType, it returns nothing.
exit;
}
?>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<form name="x" action="" method="POST">
<select name="trade" onchange="$('#extra').load('?trade='+this.value);">
<option value="1">item1</option>
<option value="2">item2</option>
<option value="3">item3</option>
<option value="4">item4</option>
</select>
<input type="submit" value="SEARCH" class="submit-button btn" />
</form>
<div id="extra" style="color:red;"></div>
EDIT:
I've added a search button this time. I've echoed it out again and it seems it is working, however, it is returning an array which is not what I am after.
So once the page loads, the user will select from the dropdown and the variable $ProductType should change. If I then submit the form, the page loads again and my variable updates my query.
PHP runs on the server, jquery (javascript) runs inside the browser of the client machine, which bascially means if you inspect the html your php has created for you from inside chrome or IE, all you see is HTML and you php code will be missing, it's missing because the server has run it (on the 'server side') and used it's output to change/append the html you have included in your php.
Your html form uses the 'post' method, so when the http protocol posts (sends back) to the server, you need to use $_POST["trade"] to access the value sent from the browser on postback , php post var documentation here
Usually one adds a hidden variable to one's html form which the php can use as a check, if the form has been posted back to the server, or if no postback was received (first run) then the hidden variable will not appear in the $_POST collection of variables
I have a page which displays data for a given year.
I would like to ask the user a simple question like "what year would you like to see" via a dropdown menu.
The data set (called from a database) is defined by the single variable $year.
My current solution is to as the user the question within a form:
<form id="year" method="post" action="processing.php">
<select name="year" >
<option value="2011">2011</option>
<option value="2012" selected>2012</option>
<option value="2013">2013</option>
</select>
<input type="submit" value="View Year" />
</form>
The page processing.php has a single hidden field populated by the POST data $_POST['year'] and automatically submits this back to the original page, which in turn defines the variable $year via the newly received POST data from processing.php
Code on processing.php page:
$year=$_POST['year'];
echo '
<div class="hide" >
<form id="year" method="post" action="original_page.php">
<input name="year" value="'.$year.'" />
<input type="submit" onload="submitForm()" />
</form>
</div>
<script>
function submitForm()
{
document.year.submit();
}
</script>
';
Question 1:
Is this a sensible way to achieve this, is there something more elegant I could do?
Question 2:
It does not work - the secon page does not forward me back to the first page on load, what have I don wrong in my code?
Thank you!
The elegant method I think you are talking about is called AJAX. It will allow you to retrieve the data from the server without the need to switch pages at all.
See this : Your code implementing AJAX via jQuery $.get
Of course, now your processing.php script will need to retrieve the data you want to display and return it in HTML format so that the $.get callback can drop it into the retrieved_contents div.
What I need is this:
user loads the page (inputs are null)
user gives some input and submits
the inputs have their new values
user navigates back
the inputs have their previous values
My php file looks like this:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
</head>
<body>
<form id="formTest" name="formTest" action="<?php echo htmlentities($_SERVER['PHP_SELF']); ?>" method="post" autocomplete="off">
<select id="selectTest" name="selectTest">
<option value=0 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==0){echo 'selected=\'selected\'';} ?>>Select an option...</option>
<option value=1 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==1){echo 'selected=\'selected\'';} ?>>Option 1</option>
<option value=2 <?php if(isset($_POST['selectTest']) && $_POST['selectTest']==2){echo 'selected=\'selected\'';} ?>>Option 2</option>
</select>
<br/>
<input id="inputTest" name="inputTest" type="text" value="<?php if(isset($_POST['inputTest'])){echo htmlentities($_POST['inputTest']);} ?>" />
<br/>
<input type="submit" value="OK" />
</form>
<?php
print_r($_POST);
?>
</body>
</html>
As you can see the form "remember" its data after a submit. The problem occurs at this point when the user hits the browser's Back button. Although the POST array has the values of the previous state, the browser fills the fields with the data of the next state (with the ones after the submit).
Although I could managed this problem in Chrome and Firefox with turning off the autocomplete property of the form, but this had no result in IE8.
Any suggestions would be much appreciated!
It sounds like you want the form always to display the values you echoed in your PHP? A quick-and-dirty fix is to reset the form when the page loads:
<body onload="document.forms[0].reset();">
You might need to update that onload attribute for different page structures or you could do it more elegantly if your actual application used jQuery and you give the form an ID.
I believe there is a way to turn off autocomplete/history per-field in IE also. I'd have to google that. Edit: Okay, I did... looks like you have the form attribute IE is looking for. I don't think this is actually an autocomplete issue so much as the back button is trying to recreate the last state of the page... including changes the user made, specifically filling out fields.
Here's the jQuery approach to resetting the form when the document is ready (include back button)... strangely, jQuery hasn't implemented the reset() method of a form, so the [0] gets you the raw DOM element. Add these lines to your head; substitute a local jquery on your server if available and preferred:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script>
$(function(){$("#formTest")[0].reset();});
</script>
If you run them through some sort of persistent struct (session scope comes to mind) , you can set that to a conditional on your form. So if it doesn't see the form variable (which is what post is for passing and interrogating form stuff). So the statement would replace the post isset and instead check if the struct 'session' (or some other scope) exists and if so populate. Make sense? I hope this helps.
I've written an HTML page that contains a form. The form is checked by a PHP page by having at the beginning of the HTML page :
<script type="text/javascript" src="js/mootools/core.js"></script>
<script type="text/javascript" src="js/mootools/more.js"></script>
<script type="text/javascript" src="js/formcheck/lang/fr.js"> </script>
<script type="text/javascript" src="js/formcheck/formcheck.js"> </script>
<script type="text/javascript">
window.addEvent('domready', function(){
new FormCheck('form');
});
</script>
The problem is that I add dynamically a class to an HTML element after the page is loaded under some conditions.
The following code sample of the HTML page is a radio button to know if the visitor of the page has a car. If she/he puts yes then the class 'validate['required']' is added to select element number of cars meaning the user must choose a value (number of cars). Otherwise the user has no car and then doesn't have to choose and the default empty string is accepted and transmitted.
<input type="radio" name="cars" value="yes" onclick="document.getElementById('number_of_cars').setAttribute('class','validate[\'required\']');">oui
<input type="radio" name="cars" value="no" checked="checked">no
<label>How many cars do you have ? :</label>
<select name="number_of_cars" id="number_of_cars">
<option value="">-</option>
<option value="01" >01</option>
<option value="02" >02</option>
<option value="03" >03</option>
</select>
The problem I have is that when I check with Firebug the HTML element has the class 'validate['required']' when needed (radio button yes) but the PHP page doesn't seem to work because the form is transmitted even if the user hasn't choosed a number of cars.
My guess is that the event "domready" on the Javascript part of my HTML page is not appropriate but I don't know what to do.
Edit: I've changed the javascript element to onChange but it doesn't work neither.
The window.addEvent('domready') is part of the MooTools library, it is not part of Javascript itself. It seems to me that you are not using that, so you should either add the MooTools script to your html, or use the onLoad event.
MooTools is used
Edit
Either that, or the value you send with the FormCheck object is wrong. FormCheck needs an id and not a tagname, so you should at least have somewhere:
<form id="myForm">
new FormCheck('myForm');
Edit 2
If you're already using MooTools, it's best to use the built-in event handlers. Direct approaches like onClick and onLoad should be avoided because of cross-browser issues. MooTools takes care of that.
<script type="text/javascript">
window.addEvent('domready', function(){
$('cars').addEvent('click', function() {
$('number_of_cars').addClass("validate['required']");
});
new FormCheck('form');
});
</script>
MooTools needs id's for this to work, so:
<input type="radio" name="cars" id="cars" value="yes">
Edit 3
Also read the docs of FormCheck carefully. They contain lots of sample code: http://mootools.floor.ch/en/demos/formcheck/
Docs: http://mootools.floor.ch/docs/formcheck/files/formcheck-js.html
Hope this helps