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
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!
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.
Complete newbie to web2Py.... I have a web page that has a dropdown menu and I want to perform certain queries based on the value selected.
Reports.html
<h2>Reports</h2>
<p>Please select a report template or choose to write your own.</p>
<select id="ReportSelect" onchange="ReportSelectionChange()">
<option disabled selected value="0"></option>
<option value="1">option 1</option>
<option value="2">option 2</option>
</select>
<script language="javascript" type="text/javascript">
function ReportSelectionChange()
{
var menuItem = document.getElementById("ReportSelect").value;
switch(menuItem)
{
case "1":
{{=myform}}
break;
case "2":
default:
alert(menuItem);
break;
}
}
controller python file
def reports():
user_id = request.args(0)
tuple = db(/*My query here*/).select()
myform = FORM('/*not sure what goes here*/')
return dict(tuple=tuple, myform=myform)
I want to pass back all the results from the query to the calling page and have the results appear in a table.
Q: How can I do this? what needs to get passed back? can this even be accomplished with javascript?
You are mixing HTML generated by web2py with javascript in a way that will not work. Remember that javascript is executed client side and python is server side.
In this case I suggest you start with trapped links:
http://www.web2py.com/books/default/chapter/29/12/components-and-plugins#Trapped-Ajax-links-and-the-A-Helper
Which will work well for your usage of either browsing or creating. Later you can revisit this page and make it better.
Use ajax function, the ajax function will be executed in some event ( this case onclick of the select item , then will run some method in your controller, this method in controller will return the data from db and the ajax function have parameter that means the target that result will be appended .
1.Use the ajax function on option element indicating that will executed on onclick event.
2. In method in your controller make the search on database and return the result.
3. Set the target of ajax function to some element in your html ( table , li's ...)
1.
<select id="ReportSelect" name="myoption">
<option disabled selected value="0"></option>
<option value="1" onclick="ajax('{{=URL('controller', 'method')}}', ['myoption'], 'your_target')" />option 1</option>
<option value="2">option 2</option>
</select>
2.
def method():
data = request.vars.myoption
your_result_query = db(your_query)
elements = UL(LI(content) for i in your_result_query)
return dict(result=elements)
In your view put a element with id with same name of target of ajax_function .
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.
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';