So this is what i have in html:
<p><br><form name="edit" method="post">
<div><select name="Edi" id ="Edi" >
<option selected="selected">Select</option>
<option value="1.php">Apple</option>
<option value="1.php">Bannana</option>
<option value="2.php">Carrot</option>
</select>
<input onclick="return Edit();" type="submit" value="Edit"/></div>
</form>
here is the corresponding javascript:
function Edit(){
if(document.forms['edit'].Edi.value == "Select")
{
alert("Please Select Edit Field");
return false;
}
else
{
window.open(Edi.options[Edi.selectedIndex].value);
return true;
}
}
Here is my problem. As you can see both my option Apple, and Bannana open the same php page. I want that. But i also want a variable in PHP that can store Apple/Bannana depending which was chosen in dropdown.
I tried this in PHP and it did not work.
$Table = $_POST['Edi'];
I know i can create a different PHP page for Apple(1.php) and Bannana(3.php). But in my program creating a page will just be duplicated code. (Apple and bannana just decide which table to store in). Also, i might be adding more options in the future, so i dont want to keep copying code.
What i came up with is putting the variable in javascript, but then tranfering to PHP is not possible. So I decided with creating extra layer rather than creating copied pages. (1 selected-shows apple, bananna) (2 selected-shows carrot). I can do this.
But is this the most efficient way of doing this?
You can use PHP's $_GET array to access URL parameters.
For example:
<option value="1.php?table=apple">Apple</option>
<option value="1.php?table=banana">Banana</option>
And your PHP:
$table = $_GET['table'];
If the variable could be missing, you can provide a default value by using PHP's ternary operator:
$table = isset($_GET['table']) ? $_GET['table'] : 'apple';
Related
I'm creating a cart page using PHP. I have managed to store the items that the person wants to buy in a session variable which stores an associative array that has the identifier of the item as the key and the quantity of the items as the value:
if (isset($_POST["btnSubmit"])){
$_SESSION["cart"][$isbn] += 1;
header("Location:cart.php");
}
I also managed to list these items on the cart using a foreach loop and a query:
<?php
$total;
foreach($_SESSION["cart"] as $product=>$quantity){
$query = mysqli_query($con,"SELECT * FROM BOOKS WHERE $product LIKE isbn");
$data = mysqli_fetch_array($query, MYSQLI_ASSOC);
$title = $data["title"];
$price = $data["price"];
$image = $data["image"];
$author = $data["author"];
$isbn = $data["isbn"];
print
"<a href='product.php?product=".$isbn."' class='list-group-item list-group-item-action>
<img src='".$image.">
<h5>".$title."</h5>
<h5>£".$price."</h5>
</a>
<select name='quant' id='quant'>
<option value=''>".$quantity."</option>
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
<option value='6'>6</option>
<option value='7'>7</option>
<option value='8'>8</option>
<option value='9'>9</option>
<option value='10'>10</option>
</select>";
$total += $price*$quantity;
}
?>
As you can see, there is a dropdown list that I want to use to modify the number of items purchased. I need this list to update the value of the specific key within the $_SESSION['cart'] variable and then for that quantity to dynamically multiply by the price to display a total. For this, I am using jQuery.
<script>
$(document).ready(function(){
$("#quant").change(function(){
$.get('ajax/getTotal.php',{quant:$(this).val()},function(data){
$('#total').load(data);
});
});
});
</script>
I need to know two things:
How do I update the values in the SESSION variable without affecting the other values?
How do I properly use jQuery to dynamically update the total after the values in the SESSION variable have been updated?
I really appreciate your help. I'm really new to AJAX and I am very lost.
If I get you correctly, what you are trying is impossible. PHP is run on the servers building the HTML. After the page is served to the client/browser you cannot manipulate the PHP variable anymore.
You can manipulate the HTML using JS, e.g. to change the value of a DOM Element to show the total. However, this will be only effective on the client side. Using jQuery: https://www.w3schools.com/jquery/jquery_dom_set.asp
To make such a change effective on the server side / the session (which is also handled on the server) as well you will have to send a POST request to your server.
The easiest way for this is a to wrap your isbn and quantity into a normal <form method="POST" action="/pathToSessionUpdatingScript">.
E.g. using an <input> field for the isbn and <select> for the quantity. If you want to avoid clicking a button you can submit the form using JS / JQuery using the change event like you did above.
On the server side you then simply update the session using another php script
After that you may redirect to your original page.
Hope this helps!
Im trying to pass a value from one page for a product to another page for the cart.
I've tried a few different options but haven't managed to come up with any solution.
I'm new to html and javascript so need a simple solution if thats possible so that I can understand.
Product Page
<label for="exampleFormControlSelect1">Example select</label>
<div>
<select class="form-control" id="Selected">
<option value='1'>1</option>
<option value='2'>2</option>
<option value='3'>3</option>
<option value='4'>4</option>
<option value='5'>5</option>
</select>
</div>
<button id='btn' type="button" class="btn btn-secondary">Add To Cart</button>
<script type="text/javascript">
var value=0;
function send_selected(){
var selector = document.getElementById('Selected');
var value = selector[selector.selectedIndex].value;
sessionStorage.setItem(value);
}
document.getElementById('btn').addEventListener('click',send_selected);
</script>
Cart page
<script type="text/javascript">
var value = sessionStorage.getItem("value");
document.getElementById('display').innerHTML = value;
</script>
<body>
<div id="display"></div>
</body>
I would need to value from the drop down to be passed to the cart page to work out the value for all the users products selected.
You need to add two arguments to sessionStorage: key and value. Something like this:
sessionStorage.setItem("selectValue", value);
Also, as far as I know if you work with local html files opened like path/cart.html in the browser, the sessionStorage can't help you; it's scope is limited to the page. If you serve them through localhost, you'll be alright.
If this pages have different url, you can do it with query params: https://en.wikipedia.org/wiki/Query_string
By Browser Storage Method :
As mentioned by #Ferenc, the setItem method of session storage takes two parameters.
sessionStorage.setItem("selectedItem","value");
or you can use
sessionStorage["selectedItem"] = "value";
And to retrieve the value anywhere else in the browser you can either use the getItem() method or you can go with the array like value access approach i.e.
var value = sessionStorage["selected"];
But I would suggest you go with localStorage instead of sessionStorage, Because of it's larger scope than the sessionStorage scope.
You can read difference b/w session storage and local storage here.
Note: You can check for errors in your javascript code(Which now occurs when you call the getItem method with a single parameter ) by looking in the browser console.
By Query Parameters:
Well, this is not a recommended method if you are not using any server-side language. i.e. Java, PHP etc.
In this case, you append the query string in url. i.e.
http://www.url.com?value=selected
To Read how to access query parameters by using javascript refer to this question.
It worked for me to add to the 1st HTML file:
where_from = document.getElementById("where_from").value;
sessionStorage.setItem("pass_to_other_form", where_from);
and then to the 2nd HTML file:
var from_other = sessionStorage.getItem("pass_to_other_form");
I have a very simple HTML page for testing which has a simple dropdown menu:
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<select id="mySelect" onchange="copy();">
<option value="">Select a person:</option>
<option value="Value of m1" >m1</option>
<option value="Value of m2" >m2</option>
<option value="Value of m3" >m3</option>
<option value="Value of m4" >m4</option>
</select>
<br>
<br>
<p>The value of your selected choice is: </p>
<div id="label"></div>
function copy()
{
var selected_value = document.getElementById("mySelect").value
document.getElementById("label").innerHTML = selected_value
}
</script>
</body>
</html>
Now I want to transfer the value of the selection into my python script. My python script has a function which uses the passed value as an argument to give a JSON file. I want to pass the value and then run the script to produce my JSON file when I select something. This is just for testing but my final HTML page will have multiple dropdowns similar to this one each one transferring a value to my python which would be used as an argument. Everything is done locally using local host. Any help would be appreciated!
Its a bit tricky.
You have to use a form to send the data to a PHP-Web Server.
Then use shell_exec($command) to run your Python Script with parameters.
Your PHP Script should look like this:
<?php
$input = $_GET['mySelect'];
//sanitize and check the input
$cmd = escapeshellcmd('/usr/custom/test.py -p ' . $input);
//escape the command
$output = shell_exec($cmd);
//run the script
echo $output;
?>
It's very important to sanitize and check your user input otherwise an attacker could easily get acces to your server.
See more: http://php.net/manual/en/function.shell-exec.php
Notes from php.net
This function can return NULL both when an error occurs or the program produces >no output. It is not possible to detect execution failures using this function. >exec() should be used when access to the program exit code is required."
This function is disabled when PHP is running in safe mode.
I'm trying to pass a value of a option in a select from my HTML form to a PHP variable through Javascript
<script type="text/javascript">
function changeDir(ID){
var dir = document.getElementById(ID).value;
//For debuging purposes i've used an alert to show the value of dir on screen
//alert (dir);
//At this point of the function I want to assign the value of "dir" to the variable $folder
}
</script>
there's my .php with html
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<?php $folder= ...?>
I'm using this with a php upload lib, all working at the same file.
If anyone can explain me how to assign the value of the option to a php var will be great.
Thanks and Regards.
You can choose 2 different ways. First is AJAX, second is to redirect the page and GET the value of the <select> element.
HTML:
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
JAVA:
<script type="text/javascript">
function changeDir(ID){
var dir = $("course").val();
$.post("php_file.php",
{
posted_dir: dir
},
function(data){
$("id_of_result_elemnt").html(data);
});
}
</script
PHP:
<?php
$folder=$_POST['posted_dir'];
echo "This text will be display in the element with id_of_result_elemnt ID";
?>
Other method is redirect
HTML+PHP:
<SELECT name="course" ID="course" onchange='changeDir("course")' >
<OPTION value="artes>'">artes</OPTION>
<OPTION value="ingles">inglés</OPTION>
</SELECT>
<?php if (iset($_GET['folder']))
{$_GET['folder']=$folder;}...?>
JAVA:
<script type="text/javascript">
function changeDir(ID){
var dir = document.getElementById(ID).value;
window.location = "http://example.com/myphp?folder=" + dir;
}
</script>
The fact is that you can't. They both live in different parts of your page. While you can write them in the same file, all PHP code is processed in the server side and Javascript is not able to see anything from the client side.
What you could do is whether pass it as a AJAX request in order to get back some information to show to the user or make the <select> refresh the page when user changes the option by submitting the form, so you don't lose the "state" of your form, and then verify in your php block if there's any option selected.
I am trying to pass 2 values via URL to another page. I know how to do this however I am taking one of the values from the result of select box. I am grabbing the selected value and storing it in a variable then attempting to post this variable in the URL.
option 1 is storing the selected value.
<select name = 'ADDITIONALINFO' id = 'ADDITIONALINFO'>
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
<script>
var sel = document.getElementById("ADDITIONALINFO");
sel.onchange = function()
{
var option1 = sel.options[sel.selectedIndex].text;
alert(option1);
};
</script>
<?php
echo "<div class=\"add-button-quote\">Get a Quotation</div>";
The problem Im having is when I click the button the URL it takes me too displays the $sku but not $option1.
If anyone can spot where Ive gone wrong I would really appreciate your advice. Thanks!
PHP is not run while the page is active, it's only run until the page is loaded. From there you have to rely on javascript.
If $product->PR_SKU and $o->OP_NAME is set by PHP you don't have to change that part, but remove OP_NAME from the url. After getting the option selected you can then add the parameter by javascript.
Notice that you might want to store the baseUrl somewhere else instead of writing like below, where you will potentially get duplicates of the parameter:
document.getElementById("your-link").href += "&OP_NAME=" + option1;
Do like this instead:
var baseUrl = <?php echo "/quotation/index.php?sku=" . $product->PR_SKU . "&OP_NAME2=" . $o->OP_NAME; ?>
var sel = document.getElementById("ADDITIONALINFO");
sel.onchange = function()
{
var option1 = sel.options[sel.selectedIndex].text;
document.getElementById("your-link").href = baseUrl + "&OP_NAME=" + option1;
};
Your div can look like this (notice the removal of option1 and the id='your-link':
<?php
echo "<div class=\"add-button-quote\"><a id=\"your-link\" href=\"/quotation/index.php?sku=" . $product->PR_SKU . "&OP_NAME2=" . $o->OP_NAME . "\">Get a Quotation</a></div>";
?>
Give the div an id and change javascript function to:
sel.onchange = function()
{
var option1 = sel.options[sel.selectedIndex].text;
document.getElementById("add-button-quote").innerHTML = "<a href='/quotation/index.php?sku=<?php echo $product->PR_SKU;?>&OP_NAME="+encodeURIComponent(option1)+"&OP_NAME2=<?php echo $o->OP_NAME;?>'>Get a Quotation</a>";
alert(option1);
};
Or give anchor an id and the same way manipulate its href attribute.
Here is an example of form with POST method with javascript onchange event -etched- directly to select tag. This should work *(haven't tested though) and if it does, it won't take a lot of Your time to adapt this to GET instead of POST.
<form id="UNIQUEID" method="POST" action="#">
<select id="ADDITIONALINFO" name="ADDITIONALINFO" onchange="document.forms['UNIQUEID'].submit();">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
<option value="4">Option 4</option>
</select>
</form>
One more thing...
USE singlequotes when mixing php and html - wherever possible and don't forget to write php close tag.. ?> - ALSO .. this -> & should be & inside href tag when url query is not -text/plain- (javascript) but -text/html-.
Example with php shortEcho:
<?= instead of <?php echo (I assume that Your server is configured to use php shorthands):
<?='<div class="add-button-quote"> Get a Quotation </div>'; ?>
HOwever, as people already stated here, $option1 variable is not going to work on the way You want.
With additional $option1=$_GET['ADDITIONALINFO']; or $option1=$_POST['ADDITIONALINFO']; (whichever You decide to use, depending on form method) somewhere in between, and before <div class="add-button-quote"> .. might work. :)
$option1 is not defined in PHP (it's a variable in JavaScript, right?) You can not mix up JS and php in that way ;)
Use onclick instead of onchange, it should do the trick...Like #Florian asks, why not using a form?
Also, you should define option1 outside onclick/onchange scope, and use it as a javascript variable, without '$', once it is not a PHP variable