How to display data with radio buttons based on drop down selection? - javascript

I'm trying to dynamically generate radio buttons with data in front of them. The data that is to be displayed in front of the radio button is based on a drop down selection, which also displays some data in a text box using javascript.
I tried taking the selected option in a string and use it in the next query, but I know I am doing it wrong.
Database Connection
$db = pg_connect("");
$query = "select account_name,account_code,address1,address2,address3 FROM
customers";
$result = pg_query($db,$query);
//NEW QUERY
$sql1= "select name from conferences";
$result1= pg_query($db, $sql1);
//END
//New Code
<select class="form-control" id="conference" name="conference">
<option value="">Select Conference...</option>
<?php while($rows1 = pg_fetch_assoc($result1)) { ?>
<option value="<?= $rows1['code']; ?>"><?= $rows1['name']; ?></option>
<?php } ?>
</select>
<br>
// END OF NEW CODE
Dropdown to select the data.
<select onchange="ChooseContact(this)" class="form-control"
id="account_name" name="account_name" >
<?php
while($rows= pg_fetch_assoc($result)){
echo '<option value=" '.$rows['address1'].' '.$rows['address2'].'
'.$rows['address3'].''.$rows['account_code'].'">'.$rows['account_name'].'
'.$_POST[$rows['account_code']].'
</option>';
}?>
</select>
Displaying data in the text area based on the selcted value using javascript. (The code works fine till here)
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;"value=""placeholder="Address...">
</textarea>
<script>
function ChooseContact(data) {
document.getElementById ("comment").value = data.value;
}
</script>
Displaying data in front of the radio buttons based on the selected option(This code works if I use some random value in the query, but not if I use the selected value 'account_code' from the previous query. I'm using POST GET method to carry the selected value)
<?php
//NEW CODE
$sql = "select order_number, order_date from orders where
customer_account_code = '3000614' and conference_code='DS19-'"; <-Data
gets displayed when put random value like this.
$code = $_GET[$rows['account_code']];
$conf = $_GET[$rows1['conference_code']];
$sql = "select order_number, order_date from orders where
customer_account_code = '$code' and conference_code= '$conf']"; <- But I
want to display the data against the selected value, i.e, the 'account_code'
in the variable $code from the dropdown select
//END
$res = pg_query($db,$sql);
while($value = pg_fetch_assoc($res) ){
echo "<input type='radio' name='answer'
value='".$value['order_number']." ".$value['order_date']."'>"
.$value['order_number'].$value['order_date']." </input><br />";
}
?>
I need to help to find a way to put the selected 'account_code' in a variable and use it in the $sql query.

Please try with this code : (It's work for me)
1- Add this line to your HTML <head>:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" type="text/javascript"></script>
2- Edit your CODE to this:
Dropdown to select the data:
<select class="form-control" id="account_name" name="account_name">
<option value=""></option>
<?php while($rows = pg_fetch_assoc($result)) { ?>
<option value="<?= $rows['address1'].' '.$rows['address2'].' '.$rows['address3'].'-'.$rows['account_code']; ?>"><?= $rows['account_name']; ?></option>
<? } ?>
</select>
Displaying data in the text area based on the selected value using jQuery:
<textarea readonly class="form-control" style="background-color: #F5F5F5;"
id="comment" rows="5" style="width:700px;" value="" placeholder="Address..."></textarea>
jQuery Code:
<script type="text/javascript">
$('#comment').val($('#account_name').val()); // MAKE A DEFAULT VALUE
(function($) {
$('#account_name').change(function() {
$('#results').html(''); // REMOVE THE OLD RESULTS
var option = $(this).val();
$('#comment').val(option);
// EDIT RADIO WITH AJAX
$.ajax({
type: "POST",
url: "path/test.php",
dataType:'JSON',
data: $('#account_name').serialize()
}).done(function(data) {
for (var i = 0; i < data.length; i++) {
// ADD RADIO TO DIV RESULTS
$('#results').append('<input type="radio" name="answer" value="'+data[i].order_number+'">'+data[i].order_date+'</input><br>');
}
});
});
})(jQuery);
</script>
after that, add this HTML to your page, to show RESULTS FROM AJAX DATA
<!-- RADIOs -->
<div id="results"></div>
3- Create a new file like path/test.php
in this file, use this CODE to return values with JSON :)
<?php
header('Content-type: application/json');
// CONNECT (JUST USE YOUR CUSTOM CONNECTION METHOD & REQUIRE CONFIG FILE IF YOU WANT)
$db = pg_connect("");
$value = explode('-', $_POST['account_name']);
// EXPLODE AND GET LAST NUMBER AFTER < - >
$code = (int) end($value);
$sql = "select order_number, order_date from orders where customer_account_code = '$code'";
$res = pg_query($db, $sql);
// CREATE JSON RESULTS
$is = '';
while($data = pg_fetch_assoc($res)) {
$is .= json_encode($data).', ';
}
// AND GET ALL
echo '['.substr($is, 0, -2).']';
?>

Related

PHP-jquery-ajax dynamic dependent selection - difficulty

I'm programming a simple form with a dynamic dependent selection. There are two files. One is a php file with html, javascript and php inside, the second is a php file to get data for the second selection and send them back in json format. In the first (and main) file I have the form with two select fields. First field is for province, second is for towns. Data are in a MySQL db, two tables, table_provinces for provinces (103 rows) and table_towns for towns (8000 rows). Normally connect to the db as usual and also link to jquery using a javascript link. First I get provinces options for the first select field, using php to get the values from table_provinces of the db. Then with the javascript " on('change',function(){ here I use ajax...}) " I pass the selected value using ajax to a php file that might extract towns from table_towns and give back (in json format) values to populate the second select field. Javascript gets correctly the selected value from the first selection field (I used an alert to know it), but nothing more happens. So this is the code.
Link to jquery:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
HTML first select field:
<form method="post" action="usemychoice.php">
<select id="province" name="province" color="white">
<option value="" selected>Select a province</option>
This is how I populate the first select field:
<?php
$sql = "SELECT * FROM table_provinces";
$result = mysqli_query($conn, $sql);
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
echo "<option value='".$row['prov']."'>".$row['extended_province']."</option>";
}
} else {
echo "Error: ..........";
}
?>
And after closing that field with a /select I have this code to get values for populating with town names the second select field:
<script type="text/javascript">
$(document).ready(function(){
$('#province').on('change',function(){
var provinceID = $(this).val();
if(provinceID){
window.alert("ok you've chosen the province "+provinceID);
$.ajax({
type:'POST',
url:'get_towns.php',
data: 'prov='+provinceID,
success:function(html){
$('#town').html(html);
}
});
}else{
$('#town').html('<option value="">Please select the province first</option>');
}
});
});
</script>
This is the get_town.php code:
<?php
//*****after a require to the connection db routine"
if(!empty($_POST["prov"])) {
$sql = "SELECT * FROM table_towns WHERE prov LIKE '%" .$_POST['prov']."%'";
$result = mysqli_query($conn, $sql);
$json = [];
if (mysqli_num_rows($result) > 0) {
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
} else {
echo "Error: .................";
}
echo json_encode($json);
}
?>
Finally I have the html code :
<select id="town" name="town" color="white">
<option value="" selected>Select province first</option>
At the end of the day, the code has something wrong because I don't get any data back from get_town.php to populate the second select field, and since I didn't see a window.alert that I've put there to check ongoing execution (you don't see it in the code posted here), it seems that is not executed. Any help?
url:'get_towns.php',
Isn't it get_town.php without plural ?
Apparently it seems that the output of get_town.php is JSON
echo json_encode($json);
but in your JS it is directly output to an html element
$('#town').html(html);
Solution:
Either modify get_town.php to send html OR modify the success function in JS to convert received JSON to proper html.
I hope this will help.
UPDATE:
Replace this part of php
while($row = mysqli_fetch_assoc($result)) {
$json[$row['prov']] = $row['town'];
}
with something
echo '<option value="" selected>Select Town</option>';
while($row = mysqli_fetch_assoc($result)) {
echo '<option value="'.$row['town'].'" color="white">'.$row['town'].'</option>';
}
and finally remove the line
echo json_encode($json);

Onchange form filter with dropdown

I am trying to create a filter for a gallery that I've created. The gallery has 5 filters using dropdown menu's. When a item is selected from one of the 5 filters it has to filter the images. When a second filter is selected it has to filter the results of the first filter and so on.
I am using the onchange='this.form.submit()' script but I don't know how to assign a certain action to it when an item is selected. This is my code at the moment of writing:
<td>
Kleur:
<form method="POST">
<select name="kleur" onchange='this.form.submit()'>
<option> -- Geen optie -- </option>
<?php while ($line1 = mysqli_fetch_array($result1, MYSQLI_ASSOC)) { ?>
<option value="<?php echo $line1['kleur']; ?>"> <?php echo $line1['kleur']; ?>
</option>
<?php } ?>
</select>
</form>
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
</br>
</td>
The following part doesn't seem to work:
<?php
if (isset($_POST['submit'])) {
$kleur = $_POST['kleur'];
$SQL = "SELECT * FROM `rozen` WHERE `kleur` LIKE '$kleur'";
$result = mysqli_query($connection, $sql);
echo $result;
}
?>
Does anyone know how to use this script? and perhaps explain how to save the selected item in the dropdown menu too?
You can add an attribute with all the information you need to filter to your images
<img filterInfo="Kleur|Geur|Bloemvorm|Gezondheid|Type|Zoeken">
then set a class for all your filters to catch the changes
$(".filters").on("change",function(){
var kleur = $('[name=Kleur]').val();
var Geur = $('[name=Geur]').val();
...
...
...
$.each($('#gallery img'),function(i,v){
var attrs = $(v).attr("filterInfo").slice("|");
if((kleur == "" || kleur == attrs[0]) && (Geur == "" || == attrs[1]) .... other filters)
$(this).show(); //or fadeIn();
else
$(this).hide(); //or fadeOut();
});
});

Parse database value in selection tag using javascript

I want get value from a database to a SELECTION box by changing another SELECTION box.
For example by changing "company" selection tag.
The value will send onChange to a PHP file.
After then i want get the value from that php file in to "f_name" Selection tag.
<select class="form-control" id="company" name="company">
<?php
$dbg=$con->db;
$sql="SELECT * FROM `company_table`";
$stmt=$dbg->query($sql);
foreach($stmt as $row) {
?>
<option value="<?php echo $row['company_id'];?>" ><?php echo $row['company_name'];?></option>
<?php } ?>
</select>
<select class="form-control" id="f_name" name="f_name">
</select>
onChange code for the "Company" Selection tag is following:
$('#company').on("change", function() {
var company_id=$(this).val();
$.post('db/project_add_to_workers_db.php',// location
{'action':'GetRow','company_id':company_id},// form name or data
function (data){// return function note 'date' is user define
alert (data);
var jsonData = $.parseJSON(window.localStorage.getItem("data"));
var $select = $('#f_name');
$(jsonData).each(function (index, o) {
var $option = $("<option/>").attr("value", o.f_name).text( o.l_name);
$select.append($option);
});
});
});

Removing one option from select dropdown generated by jquery

I am working on a very basic administrator functionality of a social network and I came across this issue of not being able to remove an option from select dropdown list that I previously generated using jquery. The dropdown list contains all users of the social network. Administrator upon clicking on "Delete account" deletes the corresponding record from the database.
Now the question being - when I click on "delete account" it works perfectly fine but the option with a username is still there in a dropdown list and is possible to be picked - when picked it obviously returns dozens of PHP warnings and errors because the record is not in a database anymore. How can I remove this option straight away? I tried something like the following, but it doesn't work.
admin_panel.php (only relevant stuff)
<select name='users' id='users'>
<option value="" disabled selected>Select user</option>
<?php
$sql = mysql_query("SELECT * FROM users WHERE id <>'".$_SESSION['user_id']."'ORDER BY username DESC") or die(mysql_error());
$userList = [];
while($row=mysql_fetch_assoc($sql)){
$username = $row['username'];
$userID = $row['id'];
$userList .= '<option name="userID" value='.$userID.'>'.$username.'</option>';
}
echo $userList;
?>
</select></br></br></div>
<div id="user_info">
<!-- generated user info table-->
</div>
<script type="text/javascript">
"$('#user_info').on('click', '#deleteAccount', function(e){
data.command = 'deleteAccount'
data.userID = $('#users').val()
$.post(theURL, data, function(result){
//Do what you want with the response.
$('#delete_account_success').html(result);
})
$("#users option[value='data.userID']").remove();
$('#delete_account_success').show();
$('#delete_account_success').fadeOut(5000);
})
</script>
processUser.php (part of a switch statement)
if(isset($_POST['command'])){
$cmd = $_POST['command'];
$userID = $_POST['userID'];
$sql=mysql_query("SELECT * FROM users WHERE id='".$userID."'");
$userData = [];
while($row = mysql_fetch_assoc($sql)){
$userData['userid'] = $row['id'];
$userData['username'] = $row['username'];
$userData['name'] = $row['name'];
$userData['date'] = $row['date'];
$userData['email'] = $row['email'];
$userData['avatar'] = $row['avatar'];
$userData['about'] = $row['about'];
$userData['admin'] = $row['admin'];
}
switch($cmd){
case 'deleteAccount':
$sql= "DELETE FROM users WHERE id =".$userID;
$result=mysql_query($sql);
echo "<img src='pics/ok.png' class='admin_updated_ok'>";
break;
}
On this line
$("#users option[value='data.userID']").remove();
You're removing any option items from #users where the value is equal to the string literal data.userID
Try changing it to
$("#users option[value='" + data.userID + "']").remove();

how manage auto-submit with the action atribute in the form

I needed make a dinamic dependent dropdown in a form,so i found this solution that uses the JS auto-submit function:
function autoSubmit()
{
var formObject = document.forms['dados'];
formObject.submit();
}
then I use the onchange event in the first dropdown to call the auto-submit function:
<label>Campus:</label>
<select name="campus" onchange="autoSubmit();">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
with this the element "campus" will be setted to be used in the second dropdown SELECT statement:
$campus = $_POST['campus'];
...
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso">
<option VALUE="null"></option>
<?php
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
</select>
this code is working,but the problem is that in this way I cant set a action atribute in the form because if i do this every time the first dropdown changes it will redirect to the action's URL.this is the form that works:
<form name="dados" method="POST" onsubmit="return validar();">
with no action atribute I cant use a submit button to send the data of all the others elements to the right URL.there is a way to this?
You should use Ajax code to populate the second dropdown values.
On Form's page:
<label>Campus:</label>
<select name="campus" id="campus">
<option VALUE="null"></option>
<?php
//Popula a lista com os cursos do DB
$sql = "SELECT id,nome FROM campus";
$countries = mysql_query($sql,$conn);
while($row = mysql_fetch_array($countries))
{
if($row[nome]==$campus)
echo ("<option VALUE=\"$row[nome]\" selected>$row[nome]</option>");
else
echo ("<option VALUE=\"$row[nome]\">$row[nome]</option>");
}
?>
</select>
<label>Curso:
<span class="small">curso corrente</span>
</label>
<select name="curso" id="curso">
</select>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#campus').change(function(){
var campusName = $(this).val();
$('#curso').load('generateCurso.php?campus='+campusName);
});
});
</script>
Write a PHP file, called generateCurso.php
<?php
$campus = $_GET['campus'];
$consulta2 = "SELECT curso FROM campus_cursos WHERE campus = \"" . $campus . "\"";
$cursoslista = mysql_query($consulta2,$conn);
?>
<option VALUE="null"></option>
<?php
while($row = mysql_fetch_array($cursoslista))
{
echo ("<option VALUE=\"$row[curso]\">$row[curso]</option>");
}
?>
I solved this issue using a ajax script triggered by "on change" event.the ajax script call a external file that return an array of elements.the script use these elements to populate the dropdown list.

Categories

Resources