Send a JavaScript variable to PHP without POST - javascript

I have a HTML modal containing a form with a select tag and an input text.
Select options are extracted from a database like this.
<select id="select_1" name="select_1">
<?php
A code that access to DB
$sql = $bdd->query('SELECT * FROM my_table;');
while(#$fetch = $sql->fetch(PDO::FETCH_ASSOC)){
$id = $fetch['id'];
$name= $fetch['name'];
?>
<option id="<?php echo $id ; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<input type="text" id="input_1">
What I'm trying to do is when I choose an option from the select tag I want to output a field from a database relative to that select option in an input text.
For example let's pretend that my_table is defined this way and contains these:
| id | name | price |
+--------------+----------------+-----------------+
| 1 | A | 500 |
| 2 | B | 1000 |
My select tag will then contains the two options A & B:
<Option 1> A
<Option 2> B
When I select Option 1 (A) I want to output it's price in the input text so it will contain 500.
When I select Option 2 (B) 1000 will be output in the input text.
How Can I do that without submiting the form with POST and without closing the MODAL?

This is what I would do
<select id="select_1" name="select_1">
<?php
$sql = $bdd->query('SELECT * FROM my_table;');
while($fetch = $sql->fetch(PDO::FETCH_ASSOC)){ ?>
<option id="opt-<?php echo $fetch['id']; ?>" data-price="<?php echo $fetch['price']; ?>" ><?php echo $fetch['name']; ?></option>
<?php } ?>
</select>
<input type="text" id="input_1">
Then you can use (jQuery)
$('#select_1').on('change', function(){
$('#input_1').val($(this).find('option:selected').data('price'));
});
There is actually no need for AJAX, because the price comes from the same table. You can simply store it as a data attribute and then access it when the select changes.
But, remember it's an attribute of the option not the select. So you need to get the option that is selected. Which we can do with the sudo-selector :selected
$('#select_1').on('change', function(){
$('#input_1').val($(this).find('option:selected').data('price'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="select_1" name="select_1">
<option id="opt-0" data-price="" >Pick an Option</option>
<option id="opt-1" data-price="500" >A</option>
<option id="opt-2" data-price="1000" >B</option>
</select>
<input type="text" id="input_1">
P.S. You are not really supposed to start an id with a number. So I added opt- to it.
Also you could just do this (use the value attribute):
<select id="select_1" name="select_1">
<?php
$sql = $bdd->query('SELECT * FROM my_table;');
while($fetch = $sql->fetch(PDO::FETCH_ASSOC)){ ?>
<option id="opt-<?php echo $fetch['id']; ?>" value="<?php echo $fetch['price']; ?>" ><?php echo $fetch['name']; ?></option>
<?php } ?>
</select>
I don't really see the need for the text input. Because when you submit this the value of select_1 in the Post or Get part of the submission will be the value of the select not the text of it.
But with out more about what you are doing, who can say.

You can do this using javascript or Jquery with and AJAX request.
Example using Jquery:
$(document).on('change','#select_1',function({
var value = $(this).value;
//DO your ajax request here and send the value inside the data
})

Because you have the values already loaded, passed into the select options values, using GlobalEventHandlers and an arrow function.
select_1.onchange = (()=> {
input_1.value = select_1.value
})
<select id="select_1">
<option value="1" selected> A </option>
<option value="2"> B </option>
</select>
<input type="text" id="input_1" value="1">

Related

how to avoid repetition of values in dropdown list while updating in php

I want to update "profile of a user" in php. There is a repetition of one value for two times in dropdown list. for example i take language value='Punjabi' from database but there is also a value placed in dropdown with name of 'Punjabi'.
The issue is simply that there is a repetition of value which i don't want.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?> '> <?php echo $queryArray["language"]; ?></option>
//for example, the value from database is "Punjabi"
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
</select>
<?php } ?>
when a value='Punjabi' from database is selected in dropdown list, the dropdown should not show the value='Punjabi' that is already placed in dropdown.
Remember: i have more than 1000 values in my dropdown(html) list.
screenshot
Instead of creating a new option according to the user data, Check if existing options are equal to user data:
<select name="language" id="language" >
<option value="Punjabi" <?php if ($queryArray["language"]=="Punjabi"){echo 'selected="selected"'} ?>>Punjabi</option>
<option value="Hindi" <?php if ($queryArray["language"]=="Hindi"){echo 'selected="selected"'} ?>>Hindi</option>
<option value="Urdu" <?php if ($queryArray["language"]=="Urdu"){echo 'selected="selected"'} ?>>Urdu</option>
</select>
If there are large number of options and you don't want to hard code these conditions, you can remove the second option using javascript on DOM ready:
$(document).ready(function(){
$('option[value="<?php echo $queryArray["language"] ?>"]').eq(1).remove();
})
skip the loop when value is equal to Punjabi, Urdu and Hindi.
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){ ?>
<select name="language" id="language" >
<?php if($queryArray["language"]!="Punjabi" && $queryArray["language"]!="Urdu" &&
$queryArray["language"]!="Hindi") { ?>
<option value="Hindi">Hindi</option>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } ?>
I think you are doing it wrong way the correct way would be having a table which stored all the languages along with values
using selected attribute to achieve your objective
<?php
$result=mysqli_query($conn, "select * from profile where id=$firstPerson");
$queryArray1=mysqli_fetch_array($result);
$langOfUser=$queryArray1["language"];
?>
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from langtab");
while($queryArray=mysqli_fetch_array($result)){ ?>
<option value='<?php echo $queryArray["languageValue"];?> ' <?php if($langOfUser== $queryArray["languageValue"]){ echo 'selected';}?>> <?php echo $queryArray["languageName"]; ?></option>
<?php } ?>
</select>
You have to use if condition to display values in select option.
<select name="language" id="language" >
<?php $result=mysqli_query($conn, "select * from profile where id=$firstPerson");
while($queryArray=mysqli_fetch_array($result)){
if($queryArray["language"]!="Punjabi") {
$opval = "<option value=" . $queryArray["language"] . ">". $queryArray["language"]. " </option> "
echo $opval;
}
?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<option value="Urdu">Urdu</option>
</select>
So your problem is that you have html hardcoded options and database options. You need to merge them into one on that website.
So you can use some javascript
elements = [1, 2, 9, 15].join(',')
$.post('post.php', {elements: elements})
But you can fill your elements like this is you don´t want to write it by hand
$("#id select").each(function()
{
allOptionsInSelect.push($(this).val());
});
Than on php side you can do
$elements = $_POST['elements'];
$elements = explode(',', $elements);
And now you have html hardcoded select on server side. Now you need to check if it doesn´t already exist when you are printing from database
You can do that like this
if(in_array(value_from_database, $elements) {
// It is so skip
} else {
// It is not, so print it
}
You can use if elseif this way.
<select name="language" id="language" >
<option value='<?php echo $queryArray["language"];?>'><?php echo $queryArray["language"]; ?></option>
<?php if ($queryArray["language"] == "Hindi") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Urdu">Urdu</option>
<?php } elseif ($queryArray["language"] == "Urdu") { ?>
<option value="Punjabi">Punjabi</option>
<option value="Hindi">Hindi</option>
<?php } elseif ($queryArray["language"] == "Punjabi") { ?>
<option value="Urdu">Urdu</option>
<option value="Hindi">Hindi</option>
<?php } ?>

Keep the selected options after submitting the form

Good morning, I have a problem that is: I can not keep several options selected after submitting the form and I would like someone to help me.
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<option value="<?php echo $reg_sql['ID_USER']; ?>"><?php echo $reg_sql['NOMEUSER']; ?></option>
<?php } ?>
</select>
<script type="text/javascript">
document.getElementById('utilizadores').value = "<?php echo $_POST['utilizadores[]'];?>";
</script>
this is my code to have the various options in the select box
You have to check if $_POST['utilizadores'] or $_GET['utilizadores'] it depends on your request type. I will use $_POST in here for explain my answer.
your select is multiple, you can use in_array function for checking that if result from db record is in array of $_POST['utilizadores']
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
**<option value="<?php echo $reg_sql['ID_USER']; ?>"
<?php
if(isset($_POST['utilizadores'])){
if(in_array($reg_sql['ID_USER'], $_POST['utilizadores'])){
echo 'selected';
}else{
echo '';
}
}
?>
>**<?php echo
$reg_sql['NOMEUSER']; ?></option>
<?php } ?>
</select>
You may be able to do it more efficiently if your database result also contains which rows are selected, but when you loop through, just add the selected="selected" attribute to the <option> tag.
Assuming your $_POST array exists in this scope, you can use the in_array function in PHP to determine if the option has been selected (docs).
The ternary based operation is as follows:
in_array($reg_sql['ID_USER'],$_POST['utilizadores']) ? 'selected="selected"' : ''
Which says "if the ID_USER is in the post array, then print the selected attribute, otherwise, print a blank string"
Putting it all together:
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<option value="<?php echo $reg_sql['ID_USER']; ?>" <?= in_array($reg_sql['ID_USER'],$_POST['utilizadores']) ? 'selected="selected"' : '' $?>>
<?php echo $reg_sql['NOMEUSER']; ?>
</option>
<?php } ?>
</select>
An example of how you can do this. Either add the "selected" string if yes or leave blank if no. You can also write selected="selected". You can do the same thing to set disabled or readonly.
<select name="utilizadores[]" id="utilizadores" multiple="multiple" class="selectpicker" data-live-search="true" data-actions-box="true" title="Utilizadores">
<?php while ($reg_sql=mysqli_fetch_array($res_sql)){?>
<?php $selected = isset($reg_sql["mi_variable"]) ? "selected" : ""; ?>
<option value="<?php echo $reg_sql['ID_USER'];?>" <?php echo $selected; ?> >
<?php echo $reg_sql['NOMEUSER']; ?>
</option>
<?php } ?>
</select>
<script type="text/javascript">
document.getElementById('utilizadores').value = "<?php echo $_POST['utilizadores[]'];?>";
</script>

How to call HTML required attribute when the value is 0?

I have a drop down list where I'm populating data from the database.
<div class="form-group">
<label>Title:</label>
<select class="form-control" name="Title" id ="titleselect" required>
<!-- <option value="" selected="selected">?</option> -->
<?php foreach ($titles as $row) {
if($this->session->userdata('status')=='active' && $this->session->userdata('Title') == $row->id) { ?>
<option value="<?php echo $row->id; ?>" selected="selected"><?php echo $row->value; ?></option>
<?php }else{?><option value="<?php echo $row->id; ?>"><?php echo $row->value; ?></option><?php } }?>
</select>
</div>
My form,
How values are populated from the database,
My database table,
I want to add a validation when the title form is populated with the value "0", which is "?", it should call the HTML required attribute.
Or I would like to disable the option with the '?' mark.
How can I do achieve this?
I have managed to find a solution to my issue. I managed to do it without any JS or Jquery. Just added an if statement.
<div class="form-group">
<label>Title:</label>
<select class="form-control" name="Title" id ="titleselect" required>
<?php foreach ($titles as $row) {
if($this->session->userdata('status')=='active' && $this->session->userdata('Title') == $row->id) { ?>
<?php if(($this->session->userdata('Title') == 0)) { ?>
<option value="" selected disabled><?php echo $row->value; ?></option>
<?php } else{?>
<option value="<?php echo $row->id; ?>" selected="selected"><?php echo $row->value; ?></option>
<?php } ?>
<?php }else{?><option value="<?php echo $row->id; ?>"><?php echo $row->value; ?></option><?php } }?>
</select>
you can use jquery like this: you can use an id for ? like id="yourZeroOption" and then
$('option#yourZeroOption').each(function() {
if ($(this).isChecked())
$("select").attr("required", true);
else
alert('this filled cannot be ?');
});
since what you asked was'nt clear enough this code might helf and if you manipulate this code you can get what you want from your code. but this for sure will give you a gist of what you should do. by the way this code does not need to submit it will show the alert before that
If this is in Laravel there is a way to catch certain number to be pass. In this case, try with greater_than rule with a custom message.
Example
$this->form_validation->set_rules('title', 'Title', 'greater_than[0]');
$this->form_validation->set_message('greater_than', 'Please select one of these value');
Note: JS validation works, But keep mind it's not always.
You should mark your <select> field as required, then the first option as disabled (and selected):
<select required>
<option value="" selected disabled>?</option>
<option value="1">Mr.</option>
<option value="2">Miss</option>
<option value="3">Mrs.</option>
</select>
This will make the first entry work as a placeholder basically.
we cant make it require with 0 value it can be done only if value=""
here is my idea,
<form action="/action_page.php">
<select required>
<option value="0">?</option>
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
<input type="submit">
</form>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("select option:selected").val("");
});
</script>
<style>

Filter Dropdown Based on Another Dropdown Selection

I have multiple dropdowns and want to filter the contents of the second dropdown based on what is selected in the first dropdown. Here is the following code that I have so far. How could I do this?
HTML/PHP:
<td>
<select id="major" onChange="updateCat();">
<?php foreach ($dropdown_major->fetchAll() as $drop_major): ?>
<option
value=""
data-name="<?php echo $drop_major ['Major Category'];?>"
>
<?php echo $drop_major ['Major Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
<td>
<select id="minor">
<?php foreach ($dropdown_minor->fetchAll() as $drop_minor): ?>
<option
value=""
data-name="<?php echo $drop_minor ['Minor Category'];?>"
>
<?php echo $drop_minor ['Minor Category'];?>
</option>
<?php endforeach; ?>
</select>
</td>
JavaScript:
function updateCat() {
var e = document.getElementById("major");
var majorSelected = e.options[e.selectedIndex];
document.getElementById("minor").value = majorSelected.dataset.name;
}
Database connection and SQL statements:
<?php
$host="xxxxxxxxxxx";
$dbName="xxxxx";
$dbUser="xxxxxxxxxxxxx";
$dbPass="xxxxxxxx";
$dbh = new PDO( "sqlsrv:server=".$host."; Database=".$dbName, $dbUser, $dbPass);
$dbh->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
$sql_major = "SELECT DISTINCT [Major Category] FROM ProductTable ORDER BY [Major Category] ASC";
$sql_minor = "SELECT DISTINCT [Minor Category] FROM ProductTable ORDER BY [Minor Category] ASC";
$dropdown_major = $dbh->query($sql_major);
$dropdown_minor = $dbh->query($sql_minor);
?>
Sorry don't have much time can't make your answer for your code but giving you an example which will surely help you. run snippet below.
HTML
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br>
<select id="second"></select>
and Javascript
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
this code will work for you but try to use JSON for sending options to user and then apply some if else statement according to user selection of first drop down.
Tip: If you have large no. of options in select statement or large no. of select statements in your code then go and learn AJAX First. its easy and simple you can learn it easily. JSON and AJAX hardly takes 2-3 days.In Ajax call function according to user selection and send data using JSON. Although Ajax increases no. of request to server but it will decrease code length. which decreases page load time, easy to maintain, and good for search engine. Google love pages with less code and more information and will help you in future too to solve lots of problems easily.
function showsecondlist()
{
var uservalue=document.getElementById("first").value;
if(uservalue==1)
document.getElementById("second").innerHTML='<option value="1.1">1.1</option><option value="1.2">1.2</option>';
else if(uservalue==2)
document.getElementById("second").innerHTML='<option value="2.1">2.1</option><option value="2.2">2.2</option>';
}
<select id="first" onchange="showsecondlist()">
<option>Select</option>
<option value="1"> 1 </option>
<option value="2"> 2 </option>
</select>
<br><br>
<select id="second"></select>

Insert from combo box using php

I am populating a combo box from database, the problem is when I select an item from the combo box and try to save to another table in the database it picks the record ID column instead of the item itself.
this is the how am populating the combo box.
<label>State</label>
<select name="state" class="state" onChange="display(this.value)" width="142" style="width: 142px">
<option value="" selected="selected">-- Select State --</option>
<?php
$query="select * from tbl_state";
$query_result=mysql_query($query)or mysql_error();
while($row=mysql_fetch_array($query_result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['state_name']; ?></option>
<?php
}
?>
</select>
<div id="show_city" style="position: relative" height:5px;>
<label>LGA</label>
<select name="city" class="lga" width="142" style="width: 142px">
<option value="" selected="selected">-- Select LGA --</option>
</select>
</div>
</p>
Database connection
$state = $_POST['state'];
$city = $_POST['city'];
$sql="INSERT INTO members (state, city)
VALUES ('$state', '$city')";
NB. am using javascript to populate the combo box.
When you submit a form, only the field name along with its value will be sent. In your case, when the user select the state and press submit, the row id will be sent as you specify the row id at the option value tag.
Either you can use <option value="<?= $row['state_name'] ?>"> ... </option>" and then get the state name ini php directly:
$state = $_POST['state'];
or leave the populating code as is now and get the state name by querying database using the record id.
$state_id = intval($_POST['state']);
$city_id = intval($_POST['city']);
$sql = "SELECT `state_name` FROM tbl_state WHERE id=$state_id";
$query_result = mysql_query($sql) or mysql_error();
$state = mysql_result($query_result, 0);
echo $state;
getcity.php
<?php
$con=mysql_connect('localhost','root','') or die('Mysql not connected');
mysql_select_db('thriftdb',$con) or die('DataBase not connected');
$state_id=$_REQUEST['state_id'];
$query="select * from lga where state_id='$state_id'";
?>
<label>LGA</label>
<select name="city" width="142" style="width: 142px">
<option value="" selected="selected">-- Select LGA --</option>
<?php
$query_result=mysql_query($query)or mysql_error();
while($row=mysql_fetch_array($query_result))
{
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['lga_name']; ?></option>
<?php
}
?>
</select>
database structure is as follows
'lga' table has...
lga_id --- state_id --- lga_name
'state' table has
state_id --- state_name
When a form sends the selected item of a combo, it sends the value of the option selected, not the text. If you want to send the text, add a hidden input for every combo, then in the onclick event of the combos, call a function that populates the text to the hidden input.
selectState = function() {
$('#hiddenInputField').val($("select[name='state'] option:selected").text());
}
Then in the server side you must get the value of the input hidden field instead of the select field.

Categories

Resources