select option dropdown onchange update variable - javascript

Here is my dilemma. A multi-select drop-down displays pre-selected options. When the user makes any changes, I'm running some code in the PHP action file (called through a submit button). I'm trying to accomplish this using a flag and updating the flag in the onchange event of "select option". The rest is working fine. I just wanted to execute the queries in action file only when the user changed selections in drop down rather than every time the form is submitted. However I'm unable to pass the flag successfully. I know I'm missing something basic and have spent two days looking at it. Any help is appreciated.
The relevant code is pasted below:
//Initialize flag
<?php
...
$multi_prog_change_flag = '0';
...
?>
//Hidden Form Element
<form action="update_u.php" method="post" id="cForm" name="cForm" onsubmit="return validateForm()" autocomplete="off">
...
<?php echo '<input type="hidden" id="email" value="'.$email.'"> ';?>
<?php echo '<input type="hidden" id="multiprogchangeflag" name="multiprogchangeflag" value="'.$multi_prog_change_flag.'"> ';?>
...
// Drop-down Element where update is triggered
<tr id="odd">
<td><select id="programName" name="programName[]" onchange="updateflag();>" multiple="multiple" size=10>
..
<option name="drop1" value ="<?php echo $data['Program_Id'] ?>" <?php if ($data[curr_prog] == '1') echo 'selected="selected"'; ?>> <?php echo $data['Program_Name'];?></option>
..
</select>
<input type="hidden" id="pNames" name="pNames" value="" />
</td>
</tr>
// Function to update flag
function updateflag() {
<document.getElementById("multiprogchangeflag").value = "1";
}
// update_u.php PHP Action File
$multi_prog_flag=mysql_real_escape_string($_POST['multiprogchangeflag']);
if ($multi_prog_flag == '1'){
$multi_prog_delete_query=mysql_query("UPDATE multi_prog_access SET is_act = '0', Updated_by = '$updatedby', update_timestamp = NOW() WHERE user_id = '$useid'");
$count = count($multi_prog_names);
for($i=0;$i<$count;$i++){
$multi_prog_ID=$multi_prog_names[$i];
$multi_prog_update_query=mysql_query("INSERT INTO multi_prog_access (user_id, Prog_id, created_by, is_act, Update_timestamp) VALUES ('$ids','$multi_prog_ID', '$updatedby', '1', NOW())");
}
}

Related

Load sql data after making a choose out a select box?

I have a question.
I want to achieve something, however, I have never done this so unfortunately I do not know how to handle this.
In my screen I fill a dropdown box with names from a sql db.
Now I would like, as soon as a name is chosen from that dropdown that the other data be loaded such as, for example, min and max values.
I would like to use these values ​​to, for example, be able to give limits to input fields.
So as soon as an entry field falls outside of the loaded values, the entry field then turns red.
However, I would like to use this without the submit button of the form being pressed.
Is this possible ? if so can someone help me with this?
The code i use to fill my selectbox is this.:
<td>
<div class="controls">
<select name="prod" id="employee" onclick="updateBottomValue(this.value);" onchange="mys1()" style="width: 245px;">
<option value="" disabled selected="selected[]" multiple="multiple">Selecteer Product</option>
<?php
$pdo = Database::connect();
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sql = "SELECT * FROM specsv1 where RActive = 'y' order by RNaam";
$q = $pdo->prepare($sql);
$q->execute(array($Id,$RNaam));
Database::disconnect();
while ($row = $q->fetch(PDO::FETCH_ASSOC)) {
echo "<option value='" . $row['Id'] . "'>" . $row['RNaam'] . "</option>";
}
?>
</select>
<?php if (!empty($ProductError)): ?>
<span class="help-inline"><?php echo $ProductError;?></span>
<?php endif; ?>
</div>
<span id="selectedValue"></span>
<input STYLE="width: 6em" name="rrss" type="text" id='rrss'>
</td>
The code i have to get the selected name is this.:
<script>
function updateBottomValue(selectedvalue) {
document.getElementById("selectedValue").innerHTML=selectedvalue;
document.getElementById('rrss').value = selectedvalue;
}
</script>
Yap it is possible.
And maybe this example ajax for what you want, feel free to modify to fit your requirements.
function viewMinMax(value){
if (value == 'a'){
tempurl = "https://api.myjson.com/bins/dv40y";
}else if (value == 'b'){
tempurl = "https://api.myjson.com/bins/egjmq";
}
$.ajax({
url: tempurl,
type: "get",
dataType: "JSON",
data: {}, //this is data you send to your server
success: function(res)
{
$('#info').show();
document.getElementById("info").innerHTML = 'Your min value: ' + res.min + ', Your max value: ' + res.max;
$('#min').val(res.min);
$('#max').val(res.max);
}
})
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="" method="post">
<select name="product_select" id="product_select" onchange="viewMinMax(this.value)">
<option value="">Select Product</option>
<option value="a">Product A</option>
<option value="b">Product B</option>
</select>
<p id="info" style="display:none;"></p>
<h3>Load the min & Max</h3>
<label for="min">Min</label>
<input type="text" name="min" id="min" value="">
<br>
<label for="max">Max</label>
<input type="text" name="max" id="max" value="">
</form>
ignore the tempurl it can be change with your action to select data based on value to your DB.
Is it possible? Absolutely. There are a few ways of going about it. One easy way is to use jQuery to fire off what's called an AJAX call as soon as the dropdown value changes. The AJAX call your PHP script and get back some HTML that it will place wherever you want it on the screen.
It's a big subject, so difficult to give you exact answers, but google jquery ajax dropdown onchange and you should be able to get enough information to get you going. One of them is the following (there are many):
jQuery Load form elements through ajax, from onchange event of drop down box

how to retain drop down values as the value selected after submit

My drop down is showing blank then when i select the value of dropdown the same value is showing, but i have to show dropdown value as select first then when I click on button the respective value should show
I am doing a Php program
<form class="form-horizontal" name="form" method="post" action="<?php $_PHP_SELF?>">
<label for="courseDisp" class="col-sm-2" style="margin-top:10px;">Course : </label>
<?php
$course="SELECT * from course";
$res= $conn->query($course);
if($res->num_rows>0)
{
echo '<select name="courseDisp" id="courseDisp" class="form-control col-sm-3" style="margin-top:8px;display:inline;padding:10px;">';
echo '<option value="0" selected> -- SELECT --</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["course_id"].'>'.$row['shortname'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
<label for="yearDisp" class="col-sm-2" style="margin-top:10px;">Year : </label>
<?php
$year="SELECT distinct(year) from syllabus";
$res= $conn->query($year);
if($res->num_rows>0)
{
echo '<select name="yearDisp" id="yearDisp" class="form-control col-sm-3" style="margin-top:8px;display:inline;padding:10px;">';
echo '<option value="0">-- SELECT --</option>';
while($row=$res->fetch_assoc())
{
echo '<option value='.$row["year"].'>'.$row['year'].'</option>';
}
echo '</select>';
} else {
echo "0 result";
}
?>
<script type="text/javascript">
document.getElementById('courseDisp').value = "<?php echo $_POST['courseDisp'];?>";
document.getElementById('yearDisp').value = "<?php echo $_POST['yearDisp'];?>";
<input type="submit" class="btn col-sm-2" style="margin-left:15px;margin-top:10px;width:60px;font-weight:bold;font-size:15px;" value="GO" name="btnGo" id="btnGo" />
</form>
I think you are doing it in a wrong way:
your code should look like this
<script type="text/JavaScript">
var valueSelected=document.getElementById('course').value;
alert(valueSelected);// do here according to the need
</script>
This is because there is no $_POST variables present before you submit a form.
$_POST variables can only be 'accessed' whenever a POST form is submitted, so when the form is not submitted, $_POST['course'] will be undefined. If you want to use persistant, but also relative variables, use $_GET.
This can be done the following way:
<script type="text/javascript">
document.getElementById('course').value =<?php echo $_GET['course'];?>";
</script>
(this will cause an error if value is not set, make sure to make exceptions for that, using if statements in PHP)
but the value also needs to be fetched from the URL.
so your url needs to have ?course=<course_value> in it, for example:
https://example.com/index.php?course=Course%201
Click here for more about POST vs GET requests
Instead of setting the value with javascript, you should directly write the selected attribute.
<select name="course">
<?php foreach ($options as $key => $value): ?>
<option value="<?= $key ?>"<?php if ($key == $_POST['course']) echo " selected" ?>>
<?= $value ?>
</option>
<?php endforeach; ?>
</select>
If you have to do this in javascript, keep sure, you use the correct syntax. Your example has a wrong " at the end of the line. Also you should use json_encode, if you want to output vars into javascript. And a last thing - if you don't put this inside the document ready event, the script has to be placed after the select element, which you wan't to manipulate
<select name="course">...</select>
...
<script type="text/javascript">
document.getElementById('course').value = <?= echo json_encode($_POST['course']) ?>;
</script>
Needed to keep the <option value="">-Select-</option>

How to keep php $_GET value from a submit button after form submit from javascript?

I have a php page with 2 submit buttons and 2 radio buttons:
<?php
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
?>
<form method="get">
<button type='submit' name='choice' value='1'>Choice1</button>
<button type='submit' name='choice' value='2'>Choice2</button>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If I click on Slovenian radio button, I get:
http://localhost/index.php?language=Slovenian
If I then click on Choice2 submit button, "language" is saved and I get:
http://localhost/index.php?choice=2&language=Slovenian
If I then click on English radio button, "choice" is not saved and I get:
http://localhost/index.php?language=English
This is my first php page and after hours of googling i added this line:
<input type="hidden" name="choice" value="<?php echo $choiceIdx; ?>">
The "choice" is now saved, but i get:
http://localhost/index.php?choice=1&language=Slovenian&choice=2
I don't want it twice in url. Please explain what i am doing wrong. Thank you!
EDIT: I want to use GET (and not POST) because the URL has to be saved as a bookmark.
Here is an alternate version (as a followup to my first answer) that updates the hidden value when clicking the choice-button:
<script>
function setChoice(val) {
document.getElementById('hiddenChoice').value=val;
}
</script>
<form method="get">
<button type='submit' onClick="setChoice(1);">Choice1</button>
<button type='submit' onClick="setChoice(2);">Choice2</button>
<input type='hidden' id='hiddenChoice' name='choice' value='<?php echo $choiceIdx; ?>'>
<input id="English" type="radio" name="language" value="English" <?php echo ($language=='English')?'checked':'' ?> onchange="this.form.submit();" />
<label for="English">English</label>
<input id="Slovenian" type="radio" name="language" value="Slovenian" <?php echo ($language=='Slovenian')?'checked':'' ?> onchange="this.form.submit();" />
<label for="Slovenian">Slovenian</label>
</form>
If you have more values to retrieve you might want to create a more sofisticated and less specific js-function. You could easily pass in the id of the target input f.e.
Also you should rethink if it's realy neccessary to always submit the form, or if it might be better to first collect all the data and only send one form back to the server.
Add that to your form:
<input type='hidden' name='choiceStored' value='<?php echo $choiceIdx; ?>'>
This will store the last received val for choice and re-send it at the next form submit.
and change your php to:
$choiceIdx = 1;
$language = 'English';
if($_GET)
{
// eighter get new value
if(isset( $_GET['choice'] ))
{
$choiceIdx = $_GET['choice'];
// or if we don't have a new value, take the 'stored' one:
} elseif (isset($_GET['choiceStored']))
{
$choiceIdx = $_GET['choiceStored'];
}
if(isset( $_GET['language'] ))
{
$language = $_GET['language'];
}
}
You are passing the same name twice. 'choice' has been defined as both the hidden value name and the button value name. To be able to differentiate, you should change the hidden value name to something like 'savedchoice'. And reference it by that name

php - select option value not passed to post

Im pretty stuck at this code, I really can't see why it should not work, i don't know if some javascript code im running beforehand is interfering?
Only showing relevant part of the code
The first section with javascript updates page when selecting another dropdown, and is placed before the code that im struggling with:
`
<script type="text/JavaScript">
function changeDropDown(){
var elLocation = document.getElementById('form_location_id');
var location = elLocation.options[elLocation.selectedIndex].value;
document.getElementById("form1").action = "choose.php?id=" + location;
document.getElementById("form1").submit();
}
</script>
<form id="form1" name="form1" method="post">
<select size="1" name="form_location_id" id="form_location_id" onchange='changeDropDown(this);'>
<?php
if ($chosen_id == "1") { ?>
<option value = "1" selected><?php echo "dropdown text" ?></option>
<? } else { ?>
<option value = "1"><?php echo "dropdown text" ?></option>
<?php } ?>
</select>
</form>
<form method="post" action="update.php">
<select size="1" id="choice" name="value">
<?php
while($row = mysqli_fetch_array($query)) {
$id = $row['id'];
$number = $row['number'];
>?
<option value = "<?php echo ($id) ?>"><?php echo "ID=" . ($id) . " - #" . ($number) . ""?></option>
<?php
}
mysqli_close($db_conn);
?>
</select>
<input name="submit" type="submit" value="Submit">
</form>
update.php:
<?php
if (isset($_POST['submit'])) {
$chosen_id = $_POST['id'];
}
?>
`
I've only posted the code handling the select option and the post part...
Why is the $chosen_id variable always 0 ?
The while loop works, and fill's the variable, as this is tested with echo command inside the option line
Any help is much appreciated...
$_POST['id'] and <select size="1" id="choice" name="value">
Use $_POST['value']
You are trying to print the wrong key
if you trying to get the value of form_location_id
$chosen_id = $_POST['form_location_id'];
And if you trying to get the value of choice
$chosen_id = $_POST['value'];
This is why when you post a form to php it use html name attribute as key to assign the value to $_POST Array
I'd change Update.php to
<?php
if (isset($_POST['value'])) {
$chosen_id = $_POST['value'];
}
?>
You need to use the form_location_id to get the required value. You are using the wrong key to access the data. You need to use the name of the input. In this case, the input is the select and the name of that is form_location_id. So, you need to do this.
$value = $_POST['form_location_id'];
Try it out and do let me know if it worked out for you.
Thanks for everyone posting idea's - i've actually got it working, the code was actually working, only error was a misplaced tag, which was placed inside a tag, when placed outside this tag it works ;)

Multiple forms with AJAX on one page

I am developing a list of submissions in the admin area of my website, which I can approve/disprove with a form, with an ID of the submission in a hidden input, and the select box with Approve/Reject in. When the select box is changed, the ajax submits the form, along with the hidden ID input, then the PHP script edits the submission in the database.
It was all working fine with one submission (1 form) on the page, but now there is more than one form, it is POSTing the wrong values to the PHP script.
<tbody>
<?php
// connect to mysql
mysql_connect('#######', '#######', '#######');
mysql_select_db('jcvideos');
// query
$query = mysql_query("SELECT * FROM videos");
// loop thru
while($row = mysql_fetch_assoc($query)) {
?>
<tr<?php if($row['accepted']==0) {echo " class='warning'";}?>>
<td><?php echo $row['id'];?></td>
<td>
<a href="//youtu.be/<?php echo $row['ytid'];?>" target="_blank">
<?php
$url = "http://gdata.youtube.com/feeds/api/videos/". $row['ytid'];
$doc = new DOMDocument;
$doc->load($url);
echo $doc->getElementsByTagName("title")->item(0)->nodeValue;
?>
</a>
</td>
<td><?php echo $row['date'];?></td>
<td>
<a href="mailto:<?php echo $row['submitter'];?>">
<?php echo $row['submitter'];?>
</a>
</td>
<td>
<form id="form<?php echo $row['id'];?>" class="reviewform" method="post" action="review.php">
<input type="hidden" value="<?php echo $row['id'];?>" name="vidid">
<select name="status">
<option value="0"<?php if($row['accepted']==0) {echo ' selected';}?>>Pending review</option>
<option value="1"<?php if($row['accepted']==1) {echo ' selected';}?>>Rejected</option>
<option value="2"<?php if($row['accepted']==2) {echo ' selected';}?>>Accepted</option>
</select>
</form>
</td>
<td><?php echo $row['showdate'];?></td>
</tr>
<?php
} // end of loop
?>
</tbody>
</table>
<?php include('../includes/footer.php');?>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script src="//netdna.bootstrapcdn.com/bootstrap/3.0.0/js/bootstrap.min.js"></script>
<script src="http://malsup.github.com/jquery.form.js"></script>
<script>
$("select").change(function(){
$('.reviewform').ajaxSubmit();
});
</script>
I tried using IDs, then it didn't POST at all. What am I missing here?
You can try this assign common class like i have assigned in fiddle (status) to selectbox then get the form by the change of its children (<select>) like in fiddle i tried to get the id of from by change event of its child element (<select>) ,once you got the id get the data of form and submit it
$('.status').on('change', function(){
var id=$(this).parent("form").attr('id');
alert(id)
$('#'+id).ajaxSubmit();
/* $("#"+id).serialize() form data */
});
See Fiddle
It depends on your event listener/selector:
$("select").change(function(){
$('.reviewform').ajaxSubmit();
});
This will always submit .reviewform even if a select of anoter form has been changed.
(Basicly it registers the function for the change event of all select tags in you page)
Please try:
$(".reviewform select").change(function(){
$('.reviewform').ajaxSubmit();
});
$(".anotherform select").change(function(){
$('.anotherform').ajaxSubmit();
});

Categories