In a drop down select field I pull several options based on a mysqli query
Once I select them, I use javascript to pick up the variables and infill form fields
Once I select the desired option, a form field infills with a reference number
I want to use that reference number for another select field to query the DB for a separate list
Here is the select to get the ref #
<select id="cdetail" name="cdetail"><option value="">Select</option>
<?
$mlo="SELECT * from client WHERE loan_originator ='$uname'";
$mlo_res = mysqli_query($dbc, $mlo);
while ($row = $mlo_res->fetch_assoc()){
echo "<option value=" . $row['filename'] . ">Filename: " . $row['filename'] . "</option>";
?>
</select>
Once I make the choice from the client table, I will see the filename in the 'cdetail' form field
I want to add another select field to pull from another table based on the selection in the above select option
<select id="ndetail" name="ndetail"><option value="">Select</option>
<?
$filename = $row['filename'];
$quote1="SELECT * from nclient WHERE filename ='$filename'";
$quote_res = mysqli_query($dbc, $quote1);
while ($row1 = $quote_res->fetch_assoc()){
echo "<option value=". $row1['ln_amt'] . ">Loan Amt: " . $row1['filename'] . "</option>";
?>
</select>
Trying to pull the filename from the 1st query and creating a global variable did not work the way I coded it.
I was able to use javascript to push the value into a separate field:
<script>
$('#cdetail').on('change', function () {
var x = $('#cdetail option:selected').val()
$('#flnm').val(x);
});
</script>
This will populate (on change) the flnm field with the filename, but I have not been able to grab that input and convert it into a php variable
i.e.
<? $filename = $('#flnm').val(x); ?>
or
<? $filename = ('#flnm').val(x); ?>
or
<? $filename = val(x); ?>
or
<? $filename = flnm; ?>
Short answer: No, you can't pass variables from javascript to php like that.
But you can do it the other way around (passing php variable to javascript in a php file):
<script>
var variable = '<?= $phpVariable ?>';
</script>
What you can do, is to use AJAX requests to pass the javascript (client side) variables to php (server side).
Related
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);
I have run into a problem and Im not sure where to start... So my problem is- I need to use a dropdown which is automatically populated by a query concatenating two fields to make a single full-name. Then based off the name of the person selected change the value of the text input to be the dob, then also update every change when a new name selected. I have tried using the onchange event for select but just cant work out the right combination.
<?php
$conn = new mysqli('localhost', 'username', 'password', 'database') or die ('Cannot connect to db');
$result = $conn->query("SELECT id, dob, CONCAT(`space`,`firstname`,`lastname`) AS `whole_name` FROM `table`");
echo "<select name='id'>";
while ($row = $result->fetch_assoc()) {
$data = $id
unset($id, $name);
$id = $row['id'];
$name = $row['whole_name'];
echo '<option value="'.$id.'">'.$name.'</option>';
}
echo "</select>";
?>
<input type="text" id="text" value="<?php echo "$data" ?>"/>
Things to note - due to the concatenate needing a separator 'space' has been added to a field. at this time the sql query works exactly as intended. When loading the page in the current state the text field comes up with the correct value for the first name, but does not update when changing value of select.
Im new with PHP and mySQL - self learning as I go. Any help appreciated.
Ajax not needed here. You can just put the dob value as special attribute for each options, and then change the text input with javascript when the select value change.
Here the new select with dob in attribute :
while ($row = $result->fetch_assoc()) {
$data = $id
unset($id, $name);
$id = $row['id'];
$dob = $row['dob'];
$name = $row['whole_name'];
echo '<option dob="'.$dob.'" value="'.$id.'">'.$name.'</option>';
}
and then update the input when the select change, here an example with jquery :
$("select[name=id]").change(function(event) {
//get the dob attribute
var dob = $('option:selected', this).attr('dob');
// update the text input
$("input#text").val(dob);
});
I have a web program where the goal is plot data points for a certain Kiln that the user has selected. My problem is when a user wants to select a new Kiln, how can I update all the separate JSON pages to where the data is pulled from the new table they selected?
Here is my drop down list creater code.
<p class="navleft">
Kiln Number:<br>
<select name="kilns" id="kilns">
<?php
$sql = "SHOW TABLES FROM history";
$result = mysqli_query($con,$sql);
while($table = mysqli_fetch_array($result)) { // go through each row that was returned in $result
echo ("<option value='". $table[0] . "'>" . $table[0] . "</option>");
}
?>
</select>
</p>
And here is one of the php pages where I select all the data from a value in a table and turn it into a JSON file.
<?php
$con = mysqli_connect("localhost","KilnAdmin","KilnAdmin","history");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
mysqli_select_db($con,"history") or die ("no database");
//Fetch Data
$query = "SELECT * FROM k1_history LIMIT 1000";
$result = mysqli_query($con,$query);
if ($result) {
$data = array();
while($row = mysqli_fetch_assoc($result)) {
//$data[] = $row;
$data[] = array(
"date" => $row[ 'Timestamp' ],
"value" => $row[ 'DryBulbFront' ]
);
}
echo json_encode($data);
}
else {
echo "Error";
}
?>
Where is says k1_history, how can I get that to be the selection from the user in the dropbox menu from the other page?
In this kind of scenario you have to strongly pay attention to avoid SQL injection. Use a whitelist approach as mentioned by Konstantinos Vytiniotis and check this out How can I prevent SQL injection in PHP?
If I understand correctly what you want, then what you need is Ajax.
You have to populate the select like you do and on each select, make an Ajax call to a .php where you will handle what the user has chosen. In your case this .php file is going to take the table name the user chose, run a query and return some results back to the html. For demonstration purposes, I'll explain with an example.
Let's say in your .html you have a select like this:
Select Value:
<select name="kilns" id="kilns">
<option value="1">Option 1</option>
<option value="2">Option 2</option>
<option value="3">Option 3</option>
</select>
What defined in the value property of the option is what you are gonna pass to the .php file I mentioned. To do that, you use Ajax, so inside some script tags you have:
$('#kilns').on('change', function(e) {
var data = {'kilns': this.value};
$.ajax({
type: 'POST',
url: 'submit.php',
data: data,
dataType: 'json'
}).done(function(msg) {
alert(msg);
});
});
What this does is that every time a user selects something from the select, then this function is called, where the select's value (var data = {'kilns': this.value};) is being sent to a file named submit.php, via POST. The submit.php could look like this:
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
$kilns_error = 0;
if (isset($_POST['kilns']) && !empty($_POST['kilns'])) {
$kilns = $_POST['kilns'];
} else {
$kilns = null;
$kilns_error = 1;
}
if ($kilns_error != 1) {
echo json_encode($kilns);
}
}
What happens here is after we check we have indeed a POST REQUEST, we check whether the value is undefined or empty. After this simple check, we proceed to echo json_encode($kilns); where we return the value that we initially sent to the .php script, which in fact is the value the user selected.
In your case, what you have to do it to actually do some things in the .php script and not just return the value that you called it with. Also, make sure to pass the value you take through a whitelist to ensure that the user selects an actual table and is not trying to create problems for your database, cause it would be really easy to just change the value of what he is going to select before actually selecting it. Have a look at the prepared statements of the mysqli and PDO.
Currently my dependent list is working on $_GET request. I'm trying to convert $_GET request to $_POST in Ajax without reloading the form. In the head I put #$cat=$_GET['cat']; I want this to be like $_POST and below ajax script is working on self.location which means its getting the value from $_GET url. I want the below script to work like $_POST and without reloading the form. Any help would very much appreciated.
my global declaration on the top as below
#$cat=$_GET['cat'];
my sql queries as below
<?php
# category and sub-category
$quer2="SELECT DISTINCT name,id FROM tblproductgroups order by name";
if(isset($cat) and strlen($cat) > 0){
$quer="SELECT DISTINCT sub_group_name,id FROM tblproductsubgroups where group_id=$cat order by sub_group_name";
}else{$quer="SELECT DISTINCT sub_group_name,id FROM tblproductsubgroups order by sub_group_name"; }
?>
my ajax script as below
<SCRIPT language=JavaScript>
function reload(form)
{
var val=form.cat.options[form.cat.options.selectedIndex].value;
self.location='product-add.php?cat=' + val ;
}
function disableselect()
{
<?Php
if(isset($cat) and strlen($cat) > 0){
echo "document.myForm.subcat.disabled = false;";}
else{echo "document.myForm.subcat.disabled = true;";}
?>
}
</script>
my dependent drop down list as below
<?php
echo "<select name='cat' onchange=\"reload(this.form)\"><option value=''>Select one</option>";
$sql = mysqli_query($customCon, $quer2);
while ($row = mysqli_fetch_array($sql)) {
if($row['id']==#$cat){echo "<option selected value='$row[id]'>$row[name]</option>"."<BR>";}
else{echo "<option value='$row[id]'>$row[name]</option>";}
}
echo "</select>";
echo "<select name='subcat'><option value=''>Select one</option>";
$sql2 = mysqli_query($customCon, $quer);
while ($row2 = mysqli_fetch_array($sql2)) {
echo "<option value='$row2[id]'>$row2[sub_group_name]</option>";
}
echo "</select>";
?>
Use jQuery (see their site for installation instructions) and add a change event handler to your select item. Also add an container div to your HTML code that will hold your dynamically loaded content like:
<div id="myCatContainer"></div>
In the event handler do:
$('#myCatContainer').load('product-add.php?cat=' . $('#mySelect').val();
Be sure to read about jQuery and how to define an event handler, before you try the above code!
I don't know much about Javascript and Jquery, but I do have to use it on a HTML select tags. I have two database tables, grouptypes and groups. A grouptype can have multiple groups, but a group only belongs to one grouptype. I have two select tags, one is grouptypes and another one is groups. What I want to do is that whenever a user select a grouptype in the grouptypes dropdown menu, it triggers a handler to retrieve the corresponding groups that belong to that grouptype. I need javascript or Jquery to get it done, but I am not able to write it myself. So anyone can help me? I would so appreciate it.
GroupType: <select name="groupType">
<?php foreach($grouptypes as $type) : ?>
<?php echo "<option value='" . $type['name'] . "'>" .$type['name']. "</option>"; ?>
<?php endforeach ?>
</select><br />
Group: <select name="groups">
<?php foreach($groups as $group) : ?>
<?php echo "<option value='" . $group['name'] . "'>" .$group['name']. "</option>"; ?>
<?php endforeach ?>
</select><br />
<?php
$query = "SELECT id, name FROM group_type";
$grouptypes = $_db->getResultsForquery($query);
$query = "SELECT id, name FROM groups";
$groups = $_db->getResultsForquery($query);
?>
Here's what I would do. It uses jquery to send a get to a page called groups.php which will return some html you can parse. Then you parse it :)
$('#grouptype-select').change(function(){ //.change will detect when the select has been changed (an -option- has been chosen)
var grouptype = $(this).val(); //create a variable from the -option- chosen
$.get('groups.php', 'grouptype=' + grouptype, function(response){ //use jquery to send -get- to groups.php
$('#list-of-groups').html(response); //insert response into ur doc
}
});
Something like http://www.yoursite.com?grouptype=abc will be sent using get asynchronously (ajax) Good luck!
PS Here is a jsfiddle to get you tinkering: http://jsfiddle.net/yLyTw/1/