I have a PHP echo statement of a session value like this:
<?php echo $userinfo['RenewAgreementAmount'] ;?>
I have a form select element like this:
<select id="Lock" name="Lock">
<option value="1" selected="selected">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3 Years</option>
<option value="4">4 Years</option>
</select>
I'm trying to update the <?php echo $userinfo['RenewAgreementAmount'] ;?> output by taking what the user selects in the select value id Lock with this session value while interacting with the form?
I've tried <?php echo ($userinfo['RenewAgreementAmount'] * #Lock) ;?> with no luck.
What is the easiest way to update this value as the user interacts with the select form input in real time?
<script>
renewAmount = <?= $userinfo['RenewAgreementAmount']; ?>
function calc(year){
var amount = renewAmount*year;
// here you can perform an ajax request to update the amount on server
}
</script>
<select id="Lock" name="Lock" onchange="calc(this.value)">
<option value="1" selected="selected">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3 Years</option>
<option value="4">4 Years</option>
</select>
it's because your PHP is interpretted before your HTML. That's the whole point of PHP. One way you can work around that is to store your $userinfo['RenewAgreementAmount'] into a Javascript variable and works with this variable. EX:
<script>var RenewAgreementAmount = <?php echo $userinfo['RenewAgreementAmount'] ?></script>
And then, you can put the value of the newly created RenewAgreementAmount javascript variable where you want to show it using :
<span id="renewAgreementAmountField"></span>
<script>
document.getElementById("renewAgreementAmountField").innerHTML = RenewAgreementAmount
</script>
You can then work with your variable and change the value.
RenewAgreementAmount = RenewAgreementAmount * document.getElementById("Lock").value;
If you want to update the value on the server side, you can use an AJAX request ( XMLHttpRequest in plain Javascript) with your new variable.
Ok so you have this dropdown and you want to get the real-time options everytime something is selected:
$('#Lock').on('change',function() {
var option
option = $('#Lock').val()
$.ajax({
type: 'post',
url: "your_php_file.php",
dataType: 'data',
data: {
option: option
}
})
})
This code will get the value every time a value is selected from this dropdown and will make an ajax call to your php class that you want to handle. your php class name should be put in the url: field
After that in your php you just retrieve the data like this:
$option=$_POST['option'];
Well this means that you execute an ajax call everytime something is selected. I propose that you put a button and trigger the ajax when the user clicks the button, so setup and onClick event.
Don't forget in your html-head to include the jquery version :
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.js"></script>
Approach using some jQuery, would be something like this--
<?php
session_start();
$_SESSION["RenewAgreementAmount"] = 50;
?>
<html>
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js" integrity="sha256-ZosEbRLbNQzLpnKIkEdrPv7lOy9C27hHQ+Xp8a4MxAQ=" crossorigin="anonymous"></script>
</head>
<body>
<select id="Lock" name="Lock">
<option value="1" selected="selected">1 Year</option>
<option value="2">2 Years</option>
<option value="3">3 Years</option>
<option value="4">4 Years</option>
</select>
<script>
$(document).ready(function() {
$("#Lock").bind("change", function(index){
var value = $(this).val();
//console.log("Changed to: " + value);
$.post("updateSessionValue.php". {"newVal": value});
});
});
</script>
</body>
</html>
For updateSessionValue.php page:
<?php
session_start();
$_SESSION["RenewAgreementAmount"] = $_POST["newVal"];
Obviously, just an example code... make sure to take all the necessary security precautions!
Related
Here's the process I want to realize:
1.on index page, select one option from the list of items;
2.submit form,directing to the index page ;
3.select label showing the default value which equals what I chose in step 1.
e.g.
<html>
<select>
<option value="1">1<option/>
<option value="2">2<option/>
<option value="3">3<option/>
</select>
</html>
On index page if I chose 1 ,and submit it and the page is submitted to itself(the index page).Now,on the index page, <option value="1">1<option/> is selected by default.
I don't know which correct direction I should go and I haven't found any solutions from the Internet yet.Anybody has any ideas??
Thanks a lot!
Using PHP function and javascript onchange:
<html>
<?php
if (isset($_POST["myselect"])) {
$myselect = $_POST["myselect"];
}
else {
$myselect = 1;
}
function isselected(A,B) {
if ($A == $B){
return "selected";
}
else{
return false;
}
}
?>
<form action="index.php" method="post">
<select name="myselect" onchange="this.form.submit();">
<option value="1" <?php echo isselected(1,$myselect) ?> >1<option/>
<option value="2" <?php echo isselected(2,$myselect) ?> >2<option/>
<option value="3" <?php echo isselected(3,$myselect) ?> >3<option/>
</select>
</form>
</html>
1st : Name attribute is must for form elements .otherwise element value would not passed to server.
2nd : Check the post value and add the selected attribute for that option like below .
<select name="select1">
<option value="">Select</option>
<option value="1" <?php echo (isset($_POST['select1']) && $_POST['select1']==1 )? 'selected':''; ?>>1</option>
<option value="2" <?php echo (isset($_POST['select1']) && $_POST['select1']==2 )? 'selected':''; ?>>2</option>
<option value="3" <?php echo (isset($_POST['select1']) && $_POST['select1']==3 )? 'selected':''; ?>>3</option>
</select>
coudn't understand your question quite well but..If you want to select any other value by default, once the page comes back to the index page, you will have to send the selected value back to the index page.
<html>
<select>
<option value="1">1<option/>
<option value="2" selected="selected">2<option/>
<option value="3">3<option/>
</select>
</html>
The above would select option 2, so you just have to set it accordingly.
So, I have a form which includes two drop-down lists: id="dd-1" & id="dd-2".
The id="dd-2" options created from the database based on the id="dd-1" selection; I am using the onChange=getChildOf(this.value) in id="dd-1" to do that.
When the user selects an option in id="dd-1" I run an ajax function which passes the value of id="dd-1" to another PHP page where it runs a MySqli query and then updates the id="dd-2".
Up to here, everything is fine.
What I need is:
Remember the user selection in id="dd-1". DONE
Get the id="dd-2" options based on the submitted value of the id="dd-1". not done
After the form submission the id="dd-2" shows no options at all. So, I have to change the selection in id="dd-1" again so the ajax getChildOf(val) function gets fired!
So, I need your help please in getting #2 done.
FYI:
The id="dd-1" select drop-down list looks smothing like:
<select id="dd-1" name="dd-1" onChange="getChildOf(this.value)">
<option value="1" <?php if(isset($_POST['dd-1'])&&$_POST['dd-1']=='1'){echo 'selected';}?> >Option 1</option>
<option value="2" <?php if(isset($_POST['dd-1'])&&$_POST['dd-1']=='2'){echo 'selected';}?> >Option 2</option>
<option value="3" <?php if(isset($_POST['dd-1'])&&$_POST['dd-1']=='3'){echo 'selected';}?> >Option 3</option>
</select>
The id="dd-2" select drop-down list looks smothing like:
<select id="dd-2" name="dd-2"></select>
The ajax function:
function getChildOf(val)
{
$.ajax({
type:"POST",
url:"get_dd2_options.php",
data: 'parentid='+val,
success: function(data){
$("#dd-2").html(data);
}
});
}
The get_dd2_options.php page looks smothing like:
<html>
<option value="-1">Please Select</option>
<?php
include_once('config.php');
// list all children
$q = mysqli_query($link, "SELECT * FROM table WHERE id = '".$_POST['parentid']."'");
while($r = mysqli_fetch_assoc($q))
{
$id = $r['id'];
$name = $r['name'];
?> <option value="<?=$id;?>" <?php if(isset($_POST['dd-2'])&&$_POST['dd-2']==$id){echo 'selected';}?> ><?=$name;?></option> <?php
}
?>
You have two options, I don't know which would be best since I'm not looking at the full code base.
Option 1: After post when you check for dd1 to be set you add another check for dd2 in php.
<?php
if (isset($_POST['dd-1']) {
/* populate dd-2 based on dd-1 value*/
}
?>
Option 2: Add the logic to populate dd2 to page load.
I am working on a project where I am stuck at a point right now. I need to change the value of a DIV live on select of the dropdown using jQuery.
Example:
I want this:-
<select name="">
<option value="10">10 clicks</option>
<option value="20">20 clicks</option>
<option value="30">30 clicks</option>
<option value="40">40 clicks</option>
</select>
<div id="chpln">Clicks: 0 clicks</div>
When I will select option 1 the value will be displayed in place of 0 in DIV live. The problem is that as this select value fetches data from the database I am not understanding how to do it.
Example:
<select name="" id="pln" class="select-box" style="margin-top: -40px;" />
<?php while($ac_fetch = mysql_fetch_array($qur_ac)){ ?>
<option value="<?php echo $ac_fetch['adclk_clicks']; ?>"><?php echo $ac_fetch['adclk_clicks']; ?> clicks</option>
<?php } ?>
</select>
jQuery that I used currently:-
$(document).ready(function(){
$("#pln").click(function(){
$("#chpln").text("Plan: <?php echo $ac_fetch['adclk_clicks']; ?> secs");
});
});
This jquery is changing the value currently but I am getting only the first value of the database i.e., 10. When I choose different option it still displays the first value from the database i.e., 10 while it should actually display the second value that is 20. Please help me. FIDDLE will be appreciated.
click is a wrong event for selection box
you can utilize change event for your result.
$(document).ready(function(){
$("#pln").change(function(){
$("#chpln").text("Plan: "+$(this).val()+" secs");
});
});
For Dropdown, click(function() is not applicable. Use change(function().
I gave you 2 way. Use any one.
I) Method - 1 (Using Ajax)
<select name="" id="pln" class="select-box" style="margin-top: -40px;" />
<?php while($ac_fetch = mysql_fetch_array($qur_ac)){ ?>
<option value="<?php echo $ac_fetch['adclk_clicks']; ?>">
<?php echo $ac_fetch['adclk_clicks']; ?> clicks
</option>
<?php } ?>
</select>
<div id="chpln">Clicks: 0 clicks</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('.select-box').change(function(){
var selectBoxClicks = $('.select-box').val();
$.ajax({url:"AjaxShowClickValue.php?selectBoxClicks="+selectBoxClicks,cache:false,success:function(result){
$('#chpln').html(result);
}});
});
</script>
Create a new page, namely AjaxShowClickValue.php.
AjaxShowClickValue.php (Make Sure, if you changing page name here. Then, change in <script></script> tag too. Both are related.)
<?
echo "Clicks: ".$_GET['selectBoxClicks']." clicks";
?>
II) Method - 2
<select name="" class='select-box'>
<option value="10">10 clicks</option>
<option value="20">20 clicks</option>
<option value="30">30 clicks</option>
<option value="40">40 clicks</option>
</select>
<div id="chpln">Clicks: 0 clicks</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$('.select-box').change(function(){
$("#chpln").text("Clicks: "+$(this).val()+" clicks");
});
</script>
use jQuery Ajax for making request to the php file..
and use on .change() rather than .click() for changing the dropdown value..
the code will be placed in JS file which make ajax call to the php file on your server..
The php file will takes some params (if any) and perform select query to the databases and return result in response.. in php use json_encode(data) for that..
These examples may also help:
http://www.plus2net.com/php_tutorial/ajax_drop_down_list.php
http://www.plus2net.com/php_tutorial/php_drop_down_list.php
You will find many other examples - Just Google It and understand the key concept!
Hope this helps.
I have an issue in checking form element SELECT at server PHP code.
I found a similar link here, but it is slightly different in discussion.
My HTML code is
<body>
<div id="header">
<h1>Please add your landed property to advertise</h1>
</div>
<div id="background">
<form name="advertiseForm" id="advertiseForm" method="post" >
<br /><br /><br />
<select name="stories" id="stories" required="required"/>
<option value="Stories" >Number of stories</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="morethan4">More than 4</option>
<select/>
<label for="stories">Please select for number of stories</label>
<div id="stories-error" class="error-box" style="color:#FF0000"></div>
<br /><br /><br />
<select name="bedrooms" id="bedrooms" required="required"/>
<option value="Bedrooms" >Number of bedrooms</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>
<select/>
<label for="numbedrooms">Please select for number of bedrooms</label>
<div id="bedrooms-error" class="error-box" style="color:#FF0000"></div>
</form>
</body>
I have two SELECT elements at my form and form elements are sent to server using AJAX using data: $("form").serialize(),.
</body>
<script>
function sendtoServer() {
$.ajax({
url: "advertisementdatavalidationatserver.php",
type: "POST",
data: $("form").serialize(),
success: function(ret){
alert(ret.message);
if(ret.error == true){
if(ret.message.indexOf("Storieserror")>=0){
$('#stories-error').css('display', 'block');
$('#stories-error').html('Please enter number of stories at your building');
}else{
$('#stories-error').html('');
}
if(ret.message.indexOf("Bedroomserror")>=0){
$('#bedrooms-error').css('display', 'block');
$('#bedrooms-error').html('Please enter number of bedrooms at your building');
}else{
$('#bedrooms-error').html('');
}
}else{
$('#stories-error').html('');
$('#bedrooms-error').html('');
}
},
error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
}
</script>
</html>
My PHP code at server side for validation is
<?php
$data = array();
$data['error'] = false;
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST['stories'] == "Stories"){
$data['error'] = true;
$data['message'][] = "Storieserror";
}
if ($_POST['bedrooms'] == "Bedrooms"){
$data['error'] = true;
$data['message'][] = "Bedroomserror";
}
}
// then echo the $data array you have built as JSON to use in jquery.
//This will be what is returned in your AJAX request
header('Content-Type: application/json; charset=UTF-8');
echo json_encode($data);
?>
The problem here is for SELECT for bedrooms, no matter how I change option values to 1,2,3,4,.., the server side always comes back as Bedroomserror, that means no matter how I change other option values, client side always send 'Bedrooms' value to server.
Stories is working fine.
What could be the problem?
EDIT:
Now I found my problem. I see the serialized data as
alert($("form").serialize());
What the serialized data is shown in the attached image, interesting thing there is there are repeated data (underlined). The first one is fine stories=3&bedrooms=2&bathrooms=2. Then there is another repeated message with bedrooms=Bedrooms&bathroom=Bathrooms, I think my PHP code caught the second one and the value is never changed.
When recreating your code for testing here, I did not encounter the problem you describe. Selecting a numbered option for bedrooms did not display an error, and the returned value was correct.
To troubleshoot this type of issue, I'd suggest the following:
Make sure the values being serialized by your sendToServer javascript function are what you expect. Output them via console.log() or similar to check that what you select in the form is actually being sent to the PHP script.
I had to makes some changes to the code you provided to get it working. My assumption here is that you already have this in place, but it's not included in your question so I've referenced the changes I made below, as they were required to get the test working:
Add a valid DOCTYPE and head tag to the HTML markup
Add an input button to the form for submission
Add a script tag which pulls in jQuery
Wrap the call to your sendToServer function in a $(document).ready(function(){}); call, triggered by a click event on the input submit element (or however you submit the form)
[Optional] I added an else section after your if statement checking the $_POST['bedrooms'] value, so that I could check what the selected value was
Hope this helps.
in your html form code place a hidden field
<input type="hidden" id="bedroomsVal" name="bedroomsVal" value="" />
in php code check value of bedroomsVal
if ($_POST['bedroomsVal'] == "Bedrooms"){
//your logic
}
in js do this
$(document).ready(function(){
$("#bedroomsVal").val($("#bedrooms option:selected").text());
$("#bedrooms").change(function(){
$("#bedroomsVal").val($("#bedrooms option:selected").text());
});
})
At the first step you need to pass the parameters from your AJAX code to PHP page. then you can check the posted value in your PHP section.
HTML
<select name="stories" id="stories" required="required"/>
<option value="Stories" >Number of stories</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="morethan4">More than 4</option>
</select>
<select name="bedrooms" id="bedrooms" required="required"/>
<option value="Bedrooms" >Number of bedrooms</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>
<select/>
JavaScript
<script>
function sendtoServer() {
$.ajax({
url: "advertisementdatavalidationatserver.php",
type: "POST",
data: {story: $('#stories').val(), bedroom: $('#bedrooms').val()},
success: function(ret){
// Any logic when return TRUE;
},error: function(){
// the AJAX request failed as in timed out / bad url etc.
}
});
}
PHP
Check the all posted parameters
<?php
if(! isset($_POST)){
// return FALSE;
}
else
{
// check the posted parameters
// write your query;
// return TRUE or retrieved value
}
?>
I have a select form that sends the value when you change the select. Unfortunately, everytime it sends it goes back to the option "10". How can I have it (for example) so you can click on the 20 option and send form and stay on 20?
Here is the code:
<form method='get' name='FormVote'>
<select name="vote" onChange="document.forms['FormVote'].submit()">
<option selected="selected" value='10'>10</option>
<option value='20'>20</option>
<option value='30'>30</option>
<option value='40'>40</option>
</select>
</form>
Any help will be greatly appreciated! Thanks!
it's staying on 10 because of the
selected="selected"
attribute in the option for 10
To have it remember where the user put it you'll need to fetch its value from the database and then do something like this in PHP:
foreach ($optionsArray as $option) {
echo '<option ';
if ($theOptionValue == $savedUserOptionValue)
echo 'selected="selected"';
echo 'value="', $theOptionValue, '>', $theOptionValue, '</option>';
}
Or you could use AJAX to send the form to the server in which case the page won't refresh and the option box will stay where it is.
Use Ajax or,
<form method='get' name='FormVote' target='hidden'>
<select name="vote" onChange="document.forms['FormVote'].submit()">
<option selected="selected" value='10'>10</option>
<option value='20'>20</option>
<option value='30'>30</option>
<option value='40'>40</option>
</select>
</form>
<iframe name='hidden' id='hidden' style='display:none' width='0' height='0' border='0'></iframe>