Echo selected option - php

How would I echo a selected option in php?
I am using HTML to create a menu list (Buy and Sell), and I want to echo 'I want to buy the book' if someone choose "buy", or echo 'I want to sell the book' if someone choose "sell".

For the PHP to have access to the option in HTML, you're going to have to post the information from the HTML page back to the PHP.
PHP runs on the server; HTML is rendered on the client. Despite the fact that you're writing the PHP and HTML in the same file, the actions taken by the user in the HTML on the client are not accessible to the PHP in the same script, unless you set the HTML up to post back the user's data to some PHP page (which can be the same PHP page).

As said previously you will need to postback data from client (HTML) to server (php). This can be done in various ways but the most common are forms or Ajax.
<form method="post" action="">
<select name="option">
<option value="buy">Buy</option>
<option value="sell">Sell</option>
</select>
</form>
<?php
If (isset($_POST['option']))
echo 'I want to ', $_POST['option'], ' the book';
?>

Related

Can you make a form with a single HTML file?

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

Update PHP variable onchange of select field

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

How can I pre-load an html form if the form has already been submitted?

I have a search website.
I want the search bar form from my home page to be visible on the results page.
What solutions are there for pre-loading all the various elements of my form?
There's 3 text fields, 2 radio buttons, and two checkboxes.
Currently I'm having to interrupt each element with a php function that will see if the $_GET['valueName'] is equal to current element option, but that seems too complex and ugly to be standard.
parallel example:
<select name="section">
<option value="free" selected="<? if($_GET['section'] == 'free'){echo 'selected';} ?>">Free</option>
<option value="under100" selected="<? if($_GET['section'] == 'under100'){echo 'selected';} ?>">Under $100</option>
<option value="under200" selected="<? if($_GET['section'] == 'under200'){echo 'selected';} ?>">Under $200</option>
<option value="any" selected="<? if($_GET['section'] == 'any'){echo 'selected';} ?>">Any price</option>
</select>
I haven't ran that to know it even works, but is there not a client-side way of populating a form?
Something like:
<input type="text" name="search" value="<?php if(isset($_POST['your_var']){ echo htmlspecialchars($_POST['your_var']);}?>">
Then for check boxes/radio you'd do a loop I believe, but I can't remember right of the top of my head.
If you want variables from a form passed to another page and shown on that page you could do something like:
<form action="new_page.php" method="POST">
<input type="text" name="search_phrase">
</form>
Then on your new_page you can load them and display them:
<?php
if(isset($_POST['search_phrase'])){ echo $_POST['search_phrase']; }
?>
This is probably the most simple way to load form data onto your new page; if you don't want to use frames, divs, or AJAX. I would have gave a more specific answer but you didn't give example code; but either way this method should work just fine.
If you want the entire search bar itself included in both pages you could put the search bar in a different php file and just import it with:
include('my_search_bar.php');
And if you think the $_GET is ugly and interrupting you can use POST (it does not put variables in your link like link.php?var=abc... Also if you check if your post variables are set at the very top of your page you can make it so all those are required before the functions will execute and display variables making the functions seem more etiquette flowing.

Calling PHP function with value from HTML Dropdown Menu

I'm in the midst of creating a website that includes shopping cart functionality and have run into an issue with passing variables back-and-forth from HTML/Javascript to PHP. I understand that these languages are fundamentally different and was hoping someone could provide some guidance. I've seen several questions on similar topics, but unfortunately have yet to find a solution that works for my situation.
I have created a multidimensional array of products in php and would like to capture the value from a dropdown menu to call a function in which the value of the dropdown corresponds to a row in the product array. My list of products appear in a HTML table. I have experimented with $_GET and $_POST, but haven't had any luck. Plus I would like to avoid adding a submit button as the print_wp_cart_button_for_product function outputs an add to cart button. The print_wp_cart_button_for_product also creates the shopping cart on the sidebar.
<TD>
<form action="<?php echo $_SERVER['PHP_SELF'];?>" method="get">
<select id="productcat1" name="productcat1">
<option value="$">--Please Select--</option>
<option value="1">Product # 1 - $1.99</option>
<option value="2">Product # 2 - $1.99</option>
<option value="3">Product # 3 - $9.99</option>
<option value="4">Product # 4 - $9.99</option>
</select>
</form>
</TD>
<TD>
<?php $currentrow = 0; ?>
<?php $currentrow = $_GET["productcat1"]; ?>
<?php echo print_wp_cart_button_for_product($products[$currentrow]["Product"], $products[$currentrow]["Price"]); ?>
</TD>
Since PHP is a server side language, it has no way of knowing what is happening in the client (i.e. what is happening live in the users browser, such as which dropdown they have selected). You will have to use javascript/ajax, either to run your function entirely, or to communicate the selected option back to the server to run the PHP function. Alternatively, you can communicate with the server without javascript/ajax by submitting the form, but you said you don't want to do that.
Good luck!

Submit button -> run .php -> popup -> refresh part of page php

On my page, I currently have a select form and attached submit button, which is generated dynamically based on the entries in my database. Here is my outputted HTML
<div id="structures">
<h1>Build</h1>
<form name="buildForm" id="buildForm" method="POST" onsubmit="buildForm();return false;">
<select name="buildID" class="buildClass">
<option value="0" selected="selected" data-skip="1">Build a Structure</option>
<option name='Town Center' value='1' data-icon='../img/structures/tc.png' data-html-text='Town Center<i>
500 minutes<br>50000 gold</i>'>Town Center</option>
<option name='Barracks' value='2' data-icon='../img/structures/barracks.png' data-html-text='Barracks<i>
25 minutes<br>1500 gold</i>'>Barracks</option>
<option name='Dragon Roost' value='3' data-icon='../img/structures/droost.png' data-html-text='Dragon Roost<i>
200 minutes<br>5000 gold</i>'>Dragon Roost</option>
<option name='Mage Hall' value='4' data-icon='../img/structures/mage.png' data-html-text='Mage Hall<i>
40 minutes<br>300 gold</i>'>Mage Hall</option>
<option name='Test Lab' value='6' data-icon='../img/structures/testlab.png' data-html-text='Test Lab<i>
1 minutes<br>10 gold</i>'>Test Lab</option>
</select>
<div id="buildSubmit">
<input class="button" type="submit" value="Submit"/>
</div>
</form>
</div>
While I am finally improving with PHP/mySQL and html/css, javascript still throws me for a loop.
When the user clicks "submit," I want a popup menu to appear, and I want to update the database based on the contents of a separate php file. Afterwards, once they close out of the pop up, I want to refresh a specific area of the page. I am using codeigniter, so I load my models functions through that to populate the page.
I would love to put more code, though honestly, its such a mess and completely worthless that instead I thought I'd ask more for a healthy guideline as to what I would have to do to implement something like this.
Examples would be amazing, but I am just trying to wrap my head around what I actually need to do to make this work.
Here's the steps I think you're trying to accomplish alongside info to perform those steps. Please clarify if I'm not understanding correctly...
After clicking the submit button...
Execute a php file which alters the DB
To do this, since you're using jQuery, you could make an ajax call to your PHP file with appropriate params that are needed for the DB update.
For an example of jQuery, PHP and mysql together, see Using JQuery AJAX and php to fetch data from a mysql database. Also see the jQuery documentation on it: jQuery.ajax
Popup window to confirm the change (using JavaScript)
var answer = confirm("Do you want to change this?")
if (answer){
// Possibly call another PHP ajax script to commit database changes...
}
else{
// Rollback database changes and do some other processing...
}
To reload the page (using JavaScript)
window.location.reload();

Categories