I am trying to fill in a dropdown list from a mysql table based on the selection on a previous dropdown.
I have looked at many questions asking how to do this and came up wit the follwing, however nothing is happening to my second dropdown when I select something from the first.
I have newStock.php with the following script in the head.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script>
<script type="text/javascript">
$(function(){
$('#field').change(function(){ //on change event
var fieldVal = $('#field').val(); //<----- get the value from the parent select
$.ajax({
url : 'process.php', //the url you are sending datas to which will again send the result
type : 'GET', //type of request, GET or POST
data : { fieldValue: fieldVal}, //Data you are sending
success : function(data){$('#field2').html(data)}, // On success, it will populate the 2nd select
error : function(){alert('an error has occured')} //error message
})
})
})
</script>
With the two drop downs created in the body:
<?php
connect('final');//connect to DB
$sql = mysql_query("SELECT * FROM stockcata");
while ($row = mysql_fetch_array($sql)){
echo '<option value='.$row['id'].'>' .$row['Catagory']. '</option>';
}
?>
</Select> </label>
<input type="text" name="addCatagory" />
<label><span>Section</span>
<Select name="field2" id="field2">
</Select> </label>
And the following process.php used to query my database and provide the options to fill in the second drop down
<?php
require("header.php");
connect('final');
$temp = $_GET['fieldValue'];
$result = mysql_query("SELECT * FROM stocksection WHERE cataID = '$temp'");
while ($row = mysql_fetch_array($result)){
echo '<option value='.$row['id'].'>' .$row['section']. '</option>';
}
?>
Nothing happens in the second dropdown, I have no idea why.
Edit.........
I tried to debug it further. My database is set up with 2 tables;
Section: ID, title, Catagory_ID
and Catagory: ID, Title
When it queries the section table it is only returning data with a Catagory_ID of 0, no matter what option I chose from the drop down
The data in the success of your ajax call is not the string you think it is. You probably want something like this:
success : function(data){$('#field2').html(data.d)}, // On success,
Try a console.log(data.d); if that doesn't work to see what you are returning.
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've looked really hard on this but I can't get my head around AJAX working with PHP.
This is what I have and when a user clicks on the dropdown I would like it to save into my database
<select>
<?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
$taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
echo " <option value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
}
?>
</select>
And this is the query i'd like to run:
INSERT INTO snagging (taskstatus, updated_at)
WHERE ID = 1234
VALUES taskStatusRow['name'], $now);
I'll give you a overall flow of AJAX here. I tried to provide comments so as to show the control flow.
<select id="selectOption"> //******* Assign an ID
<?php $taskStatus = "SELECT * FROM task_status WHERE used = 1 ORDER BY id ASC ";
$taskresults = $conn->query($taskStatus) or die(mysqli_error($conn));
while($taskStatusRow = mysqli_fetch_assoc($taskresults)) {
echo " <option value= ". $taskStatusRow['name'] ." >". $taskStatusRow['name'] ." </option>";
}
?>
</select>
jQuery + AJAX
$(document).ready(function() {
$("#selectOption").change(function(){ //** on selecting an option based on ID you assigned
var optionVal = $("#selectOption option:selected").val(); //** get the selected option's value
$.ajax({
type: "POST", //**how data is send
url: "MYPROCESSPAGE.php", //** where to send the option data so that it can be saved in DB
data: {optionVal: optionVal }, //** send the selected option's value to above page
dataType: "json",
success: function(data){
//** what should do after value is saved to DB and returned from above URL page.
}
});
});
});
Inside your MYPROCESSPAGE.php, you can access the data passed via AJAX like:
<?php
$selectedOptionVal = $_POST['optionVal'];
//DB CONNECTION STEPS
.
.
.
// You are trying to "UPDATE" a table data based on some ID and not inserting. Included both operations
// If you are INSERTING A new table entry, use below code.
//INSERT INTO snagging (taskstatus, updated_at) VALUES ('$selectedOptionVal', 'Now()');
// If you are UPDATING an existing table entry, use below code.
//UPDATE snagging SET taskstatus = '$selectedOptionVal', updated_at = 'Now()' WHERE ID = 1234;
?>
Hope it's helpful.
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.
I'm working on a MySQL update form and struggle to make a drop down selectbox that will autofill the rest of the form with data from mysql. Basically its a table that consist of users and their credentials. When updating a second table with this form i want to be able to select the username from a drop menu and let that selection autofill the rest of the credentials before moving on to the rest of the form.
Here is some of the code for setting up the select and input:
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" />
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" /> </td>
</tr>
And then some javascript
<script>
function populateData()
{
//alert('in populateData');
y = document.getElementById("selectbox");
document.getElementById("klasse").value = [y.selectedIndex];
document.getElementById("klubb").value = [y.selectedIndex];
}
</script>
The result here is a number in the <td>klubb and <td>klasse based on my selection in the drop menu.
How can i connect the arrays with that index number in the javascript so that it will show the actual data from the array ?
I've been seeking an answers for a few days now but can't find anything that answers my question.
Thanks for any help!
Well you can use AJAX for that.
For a tutorial on how to use AJAX and PHP script with Mysql This can help you.
First you need to create a PHP script that will gather the data you need for filling up the forms.
Setup the AJAX to be triggered everytime you choose something in your Drop Down List and pass its value on the PHP script you created.
On your AJAX script configure it to call the PHP script you created for retrieving the data (a value will be thrown in this script based on your drop down list).
Once you receive a response from your AJAX call just use a simple Javascript to fill up the forms based on the data your received.
Another tip is to use JQuery since it is easier for you to setup your AJAX request.
Use AJAX here.
In the populateData() function, use ajax to send the request to retrieve the user credentials & through Javascript, populate your textboxes with the retrieved values.
You could echo the two php arrays as javascript objects, and then access those in your populate function (this is the quick solution). But a better way is to ajax in the actual data
<script>
var klasse = <?=json_encode($klasse)?>
var klubb = <?=json_encode($klubb)?>
</script>
Well you can use Ajax. Make this as your form.
<?php
//DB Connect
...
// Get array of users
$select_users = "SELECT * FROM users";
if (!mysql_query($select_users)) {
die('Error: ' . mysql_error());
} //all good so far
$select_users_result = mysql_query($select_users);
?>
<select id="selectbox" name="navn" onchange="populateData(this.value)">
<option>USER</option>
<?php
$klubb = array();
$klasse = array();
while ($row = mysql_fetch_array($select_users_result, MYSQL_ASSOC)) {
echo "<option value='" . $row['navn'] . "'>". $row['navn'] ."</option>";
//echoing these vars will output all rows for the column specified...
$klubb[] = $row['klubb'];
$klasse[] = $row['klasse'];
}
mysql_close();
?>
</select>
<div id="some_container">
</div>
Your AJAX request :-
<script type="text/javascript">
$('select').on('change', function() {
var selectedVal = this.value; // or $(this).val()
$(document).ready(function() {
$.ajax({ //create an ajax request to load_page.php
type: "GET",
url: "file.php?selectedVal="+selectedVal,
dataType: "html", //expect html to be returned
success: function(response){
$("#some_container").html(response);
}
});
});
});
</script>
file.php
<?php
echo '
<tr>
<td>Klubb: </td>
<td><input id="klubb" type="text" name="klubb" class="cred_input" value="$phpValueHere"/>
</td>
</tr>
<tr>
<td>Klasse: </td>
<td><input id="klasse" type="text" name="klasse" class="cred_input" value="$phpValueHere> </td>
</tr>';
?>
In your file.php, get the value of selectedVal via $_GET['selectedVal'] and then extract data from table, after extracting echo the data in those input boxes.
I have a form on my page which includes 2 dependent drop down lists. When user selects value from 1st list, it populates the second list and user then selects value from 2nd list.
I want to submit form data to php page to insert into table in mysql, but when it submits, all data is passed EXCEPT value from 2nd list. Value from 1st list and other input fields are passed OK.
I've tried everything I know and I can't make this work. Any ideas how to implement this?
This is the form from index2.php (EDIT: simplified the form element):
<form name="part_add" method="post" action="../includes/insertpart.php" id="part_add">
<label for="parts">Choose part</label>
<select name="part_cat" id="part_cat">
<?php while($row = mysqli_fetch_array($query_parts)):?>
<option value="<?php echo $row['part_id'];?>">
<?php echo $row['part_name'];?>
</option>
<?php endwhile;?>
</select>
<br/>
<label>P/N</label>
<select name="pn_cat" id="pn_cat"></select>
<br/>
<input type="text" id="manufactured" name="manufactured" value="" placeholder="Manufactured" />
<input id="submit_data" type="submit" name="submit_data" value="Submit" />
</form>
And this is javascript:
$(document).ready(function() {
$("#part_cat").change(function() {
$(this).after('<div id="loader"><img src="img/loading.gif" alt="loading part number" /></div>');
$.get('../includes/loadpn.php?part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
$('#loader').slideUp(200, function() {
$(this).remove();
});
});
});
});
And this is php to load 2nd list:
<?php
include('db_connect.php');
// connects to db
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
$part_cat = $_GET['part_cat'];
$query = mysqli_query($con, "SELECT * FROM pn WHERE pn_categoryID = {$part_cat}");
while($row = mysqli_fetch_array($query)) {
echo "<option value='$row[part_id]'>$row[pn_name]</option>";
}
?>
I am getting $part_cat from 1st list to insertpart.php, but $pn_cat.
EDIT: this is insertpart.php (simplified and it just echos resuls)
<?php
//Start session
session_start();
//Include database connection details
require_once('../includes/db_details.php');
//DB connect
$con=mysqli_connect(DB_HOST,DB_USER,DB_PASS,DB_NAME);
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
// escape variables for security
// find part name based on ID
$part_typeID = mysqli_real_escape_string($con, $_POST['part_cat']);
$part_name_result = mysqli_query($con, "SELECT part_name FROM parts WHERE part_id = $part_typeID");
$part_row = mysqli_fetch_array($part_name_result, MYSQL_NUM);
$part_type = $part_row[0];
echo"part_type='$part_type'";
//find pn value based on id
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
$pn_name_result = mysqli_query($con, "SELECT pn_name FROM pn WHERE pn_id = $pn_typeID");
$pn_row = mysqli_fetch_array($pn_name_result, MYSQL_NUM);
$pn = $pn_row[0];
echo"pn='$pn'";
mysqli_close($con);
?>
It's still work in progress, so the code is ugly, and I know I'm mixing POST and GET that is being rectified. If I echo $pn_cat on this page there is no output, $part_type is OK.
Can you try swapping the $_GET in
$pn_typeID = mysqli_real_escape_string($con, $_GET['pn_cat']);
with $_POST?
$pn_typeID = mysqli_real_escape_string($con, $_POST['pn_cat']);
EDIT: based on asker's feedback and idea for a work-around
NOTE: This edit is based on what you suggested, even though I tested your original code and received satisfactory results (after I removed the PHP and MySQL from the code and replaced them with suitable alternatives).
The Work-Around
Here's the HTML for the hidden field:
<input type="hidden" id="test" name="test" value="" placeholder="test" />
Here's a simple Javascript function:
function setHiddenTextFieldValue(initiator, target){
$(initiator).change(function() {
$(target).val($(this).val());
});
}
You can call the above function within the function(data) { of your original code with something like:
setHiddenTextFieldValue('#pn_cat', '#test'); // note the hashes (#)
I also recommend you to hard-code the following HTML into your HTML and PHP files, right before the looping of the <option>s begin:
<option value="" disabled selected="selected">Select</option>
The above line could improve user experience, depending on how you want your code to work. Note however, that this is entirely optional.
Solved it! It was just a stupid typo, can't believe I've lost 2 days over this!
In loadpn.php instead of:
$row[part_id]
it should read:
$row[pn_id]
For some reason drop down worked, but offcourse value of pn_cat wasn't being set.
Also this works in setting 2 field values (which now I don't need but if somebody wants to know):
$(document).ready(function() {
$("#part_cat").change(function() {
$('#pn_hidden').val($(this).val());
});
$("#pn_cat").change(function() {
$('#pn_hidden2').val($(this).val());
});
});
Also changed js to post:
$(document).ready(function() {
$("#part_cat").change(function() {
$.post('../includes/loadpn.php', 'part_cat=' + $(this).val(), function(data) {
$("#pn_cat").html(data);
});
});
});
And thanks for the:
<option value="" disabled selected="selected">Select</option>
It really helps with user experience.