Im trying to use PHP+MySQL+Ajax to dynamically load options in a select but I don't know how to do it
Currently I have 2 select inside 2 forms and i need to send form 2 times, so the page will load 2 times.
I want to improve my code using ajax, so my page will load faster and will be easier to use.
Select 1 have a list of countries
Select 2 have a list of cities from the country selected in select 1
After you select the city, specific info from that city will be displayed in screen.
Form 1
<?php include_once "conn.php"; ?>
<!-- Form 1 -->
<form action="" method="post">
<select required id="Countries" name="Countries">
<?php
$sql = "SELECT distinct Country FROM cities order by 1 asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["Country"] . '">' . $row["Country"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="LoadCities" name="LoadCities" value="Load Cities" />
</form>
Form 2
<!-- Store select 1 value in variable -->
<?php
if (isset($_POST['Countries'])) {
$Countries = $_POST['Countries'];
}
?>
<!-- Form 1 -->
<form action="" method="post">
<select required id="Cities" name="Cities">
<?php
$sql = 'SELECT * FROM cities where country="' . $Countries . '"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["City"] . '">' . $row["City"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="ShowInfo" name="ShowInfo" value="ShowInfo" />
</form>
Display City info on screen:
<!-- Store select 2 value in variable and print selected options in screen-->
<?php
if (isset($_POST['Cities'])) {
$City = $_POST['Cities'];
$sql = 'SELECT * FROM cities where City="' . $City . '"';
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<p>Country: ' . $row["Country"] . '</p>';
echo '<p>City: ' . $row["City"] . '</p>';
}
} else {
echo "0 results";
}
}
?>
For Ajax to work without you refreshing or submitting the forms. You need to create separate endpoints for your ajax calls. You should have 3 files:
index.php - Display the country form, city form and city info altogether here. The country data will load by default and other data will be linked to their respective Ajax calls.
fetchCities.php - Use this endpoint to fetch the dropdown values of cities based on the selected country value.
cityInfo.php - Use this endpoint to fetch the city information based on the selected city value.
Note: You can combine fetchCities.php and cityInfo.php into a single file if you include a second parameter in your Ajax call, for eg: action: "fetchCity"
Here's what you can do:
index.php
<?php include_once "conn.php"; ?>
<form action="" method="post">
<select required id="Countries" name="Countries">
<?php
$sql = "SELECT distinct Country FROM cities order by 1 asc";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="' . $row["Country"] . '">' . $row["Country"] . '</option>';
}
} else {
echo "0 results";
}
?>
</select>
<input type="submit" id="LoadCities" name="LoadCities" value="Load Cities" />
</form>
//empty city dropdown. You may remove the form element from it if not required.
<form action="" method="post">
<select required id="Cities" name="Cities">
<option disabled selected>Select a country first</option>
</select>
</form>
//empty city info
<div id="cityInfo"></div>
<script>
//whenever someone selects a country, hit the Ajax to fetch cities.
$(document).on('change', '#Countries', function() {
const selectedCountry = $(this).val();
//run your cities Ajax here and pass selectedCountry value
$.ajax({
method: "POST",
url: "fetchCities.php",
data: {
Countries: selectedCountry
}
})
.done(function(response) {
//replace City dropdown with values returned from fetchCities.php file.
$('#Cities').html(response);
});
});
//whenever someone selects a city, hit the Ajax to fetch city information.
$(document).on('change', '#Cities', function() {
const selectedCity = $(this).val();
//run your cities Ajax here and pass selectedCity value
$.ajax({
method: "POST",
url: "cityInfo.php",
data: {
Cities: selectedCity
}
})
.done(function(response) {
$('#cityInfo').html(response);
});
});
</script>
fetchCities.php
<?php include_once "conn.php";
if (isset($_POST['Countries'])) {
$Countries = $_POST['Countries'];
$sql = 'SELECT * FROM cities where country="' . $Countries . '"';
$result = $conn->query($sql);
$returnHtml = '';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$returnHtml .= '<option value="' . $row["City"] . '">' . $row["City"] . '</option>';
}
} else {
$returnHtml = '<option disabled selected>0 results</option>';
}
echo $returnHtml;
}else{
echo '<option disabled selected>0 results</option>';
}
?>
cityInfo.php
<?php
include_once "conn.php";
if (isset($_POST['Cities'])) {
$City = $_POST['Cities'];
$sql = 'SELECT * FROM cities where City="' . $City . '"';
$result = $conn->query($sql);
$returnHtml = '';
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$returnHtml .= '<p>Country: ' . $row["Country"] . '</p>';
$returnHtml .= '<p>City: ' . $row["City"] . '</p>';
}
echo $returnHtml;
} else {
echo "0 results";
}
}else{
echo "0 results";
}
?>
Also, as Dharman mentioned, you should really use parameterized queries. I know that seems like some extra work but trust me, it will be worth your time.
(Too long for a Comment.)
Let me get this straight. On a single page:
The page is initialized with a list of all countries. (Either when building the page, or via AJAX.)
The user selects one country from a list of all the countries.
A second database lookup finds the cities in that country.
Then something is done with those cities.
That must be two lookups.
Since you mentioned AJAX, you want to do all this without reloading the page? Be aware that <form> wants to reload the page. Yes you can pervert to do AJAX, but why have <form> if you won't be submitting and reloading the page?
The complete list of cities in the world is over 3 million. Are you working with that sized table? Or some subset, such as "cities that have a Burger King in it"?
Related
I have a form that contains a checkbox and a dropdown list. I use PHP to populate the dropdown list from two MySQL tables. Which table I use depends on whether the checkbox was checked or not. But, as you can see from my code sample, I can only populate that dropdown list after I submit the form. I want to be able to keep clicking on the checkbox and keep re-populating the dropdown list without having to submit the form. I am still new to this, so, please, give me as simple a solution as possible.
PS. I have a small bug in the code that doesn't keep the checkbox checked/unchecked after I submit the form. Working on fixing it.
Thank you
<?php
$Prc_Earn = 'Prc';
if (isset($_POST['submitBtn']))
{
if (isset($_POST['chkbox']))
{
$sql = 'select distinct Symbol from price_history.quarterly_earnings_history';
$Prc_Earn = 'Earn';
}
else
{
$sql = 'select distinct Symbol from price_history.stock_symbol_list';
$Prc_Earn = 'Prc';
}
}
// Connect to the database
include ('../Connections/mysql_connect.php');
if ($dbcon)
{
?>
<form method='post'>
<label for=''>Earnings / Prices</label>
<input type='checkbox' name='chkbox' id='chkbox' <?php if ($Prc_Earn == 'Prc') { echo "checked"; };?>><br><br>
<label for='symbol'>Stock Symbol:</label>
<select name = 'symbol' id='symbol'>
<?php
$result = mysqli_query($dbcon, $sql);
if (mysqli_num_rows($result) > 0)
{
while($row = mysqli_fetch_array($result))
{ echo '<option value="' . $row['Symbol'] . '">' . $row['Symbol'] . '</option>'; }
}
?>
</select><br><br>
<button class='button' type='submit' name='submitBtn' id='submitBtn'>View Data</button><br><br>
</form>
<?php
}
?>
I'm in the middle of making a simple inventory system for keeping track of equipment going in and out of our doors. The inventory is stored in MYSQL, with a table looking like this: id name storage used location_storage location
This is all fun and games when I create a simple form with PHP, so it stays dynamic with the content from the server. I can update all values with no problem.
But for the sake of simplicity I'm looking into having a drop down menu, with a button, that creates/shows input fields in a form. The reason being is that I will have many rows in my table in the upcoming time. As the forms earlier have been made from server information, I will also need the scripts to be dynamic. Right now I'm stuck thinking about what I should do.
As of now, my code for the bits look like this:
"Static" PHP form:
<form action="<?php $_PHP_SELF ?>" method="POST">
<?php
//conn stuff
$sql = "SELECT id, name, storage, used, location FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo ' ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" />';
echo '<br>';
}
} else {
echo "0 results";
}
$conn->close();
?>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>
Check in PHP (check out is identical except for change of + and minus):
if(isset($_POST['sjekkinn'])){
//conn stuff
mysql_select_db( 'experimental' );
$newamount = $_POST['newamount'];
foreach($newamount as $key => $value){
$sql = "UPDATE inventory ". "SET storage = (storage + $value), used = (used - $value)". "WHERE ID = $key " ;
if (empty($value)) continue;
$retval = mysql_query( $sql, $conn );}
if(! $retval ) {
die('Could not update data: ' . mysql_error());
}
echo "Updated data successfully!<br>";
header("Refresh:1");
mysql_close($conn);
}
Those are all working great, but I would like to use something like the code below for a neater setup... Anyone got any advice?
Drop down list generated from MYSQL:
<form action="#" method="post">
<select name="selectinventory">
<?php
//conn stuff
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}
?>
</select>
<input type="submit" name="submit" value="Add line">
</form>
Okay, so I found my own solution.
I ended up using my table-populated drop down list as I showed you in the last code box of the question. What came to my mind was that I could simply use the jQuery show/hide function.
What I did was to make a script that told (in "readable") div 'x' to show and move when option 'x' was selected and button clicked. I will show you my complete code in the end.
That way I could have my input fields each created inside a div from my table (the same that populated the drop down list), so I could manage them easier (probably possible to do it easier - but if it ain't broken, don't fix it). These were created outside the form. When I then click the previously mentioned button, the div will move inside the form. The next one I select will end up UNDER the previous one, instead of just showing up in table-order.
Feel free to shout any questions!
Here's the complete code:
<form action="<?php $_PHP_SELF ?>" method="post">
<select name="selectinventory" id="selectinventory">
<option selected="selected">Choose one</option>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
$sql = "SELECT * FROM inventory";
$result = $conn->query($sql);
while ($row = $result->fetch_array()){
echo '<option value="' . $row["id"]. '">' . $row['name'] . '</option>';
}?>
</select>
<div id="btn">Add line</div>
</form>
<script type="text/javascript">
$(document).ready(function(){
$("#btn").click(function(){
$("#" + $("#selectinventory").val()).show();
$("#" + $("#selectinventory").val()).appendTo($(".selecteditems"));
});
});
</script>
<?php
//conn stuff
$sql = "SELECT id, name FROM inventory";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo '<div style="display:none" id="' . $row["id"]. '"> ' . $row["id"]. ' ' . $row["name"]. '<input type="text" name="newamount[' . $row["id"]. ']" /><br></div>
';
}
} else {
echo "0 results";
}
$conn->close();
?>
<form action="<?php $_PHP_SELF ?>" method="POST" name="isthisthearrayname">
<div class="selecteditems">
</div>
<input type="submit" name="checkout" value="Check out"/>
<input type="submit" name="checkin" value="Check in"/>
</form>
I want to fetch data from dropdown list. Like if I choose employee id 40 from the dropdown list it will fetch the data from database of that employee and will shown in the textboxes.
this is my dropdown code. please help me how can i get the selected value.
<?php
$con=mysqli_connect("localhost","root","","hct_db");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
?>
<label>Select Employee ID</label>
<select class="form-control" name="employee_id">
<?php
$result = mysqli_query($con,"SELECT employee_id FROM employee order by employee_id");
while($row = mysqli_fetch_array($result))
echo "<option value='" . $row['employee_id'] . "'>" . $row['employee_id'] . "</option>";
?>
</select>
First of all give some id to you select option like this:
<select class="form-control" name="employee_id" id='employee'>
Add you textbox like this:
<input type='text' name='emp_name' id='emp_name' />
Than use jquery and ajax something like this:
$('#employee').change(function(){
var selected_id = $(this).val();
var data = {id:selected_id};
$.post('getemp_name.php',data,function(data){
$('#emp_name').val(data);
});
});
getemp_name.php
if(isset($_POST['id'])){
//fire query using this id and get the name of employee and echo it
echo $emp_name;
}
<?php
if(isset($_REQUEST['submit']))
{
$value=$_POST['employee_id'];
$query = mysql_query($con,"SELECT employee_name FROM employee where employee_id=$value");
$result=mysql_fetch_array($query);
$emp_name=$result['employee_name'];
}
?>
<form action="" method="post" name="form">
<label>Select Employee ID</label>
<select class="form-control" name="employee_id">
<?php $result = mysqli_query($con,"SELECT employee_id FROM employee order by employee_id");
while($row = mysqli_fetch_array($result))
echo "<option value='" . $row['employee_id'] . "'>" .$row['employee_id'] . "</option>";
?>
</select>
<input type="submit" name="submit" value="submit">
</form>
<input type="text" value="<?=$emp_name?>" name="emp_name"/>
check this code as your need
To get your selected value, you have to reach the $_GET or $_POST supertables after the user submits the form.
So, after the submit, get it as, if you POST:
<?php
$employee_id = $_POST['employee_id']; ?>
If you GET:
<?php
$employee_id = $_GET['employee_id']; ?>
apply below function on onChange
function myFunction(mySelect) {
var x = document.getElementById("mySelect").value;
document.getElementById("demo").innerHTML = "You selected: " + x;
}
example
That depends on what you want. If you want to use the selected ID in your query AFTER DOING A POST, you can use the following query:
"SELECT *
FROM `employee`
WHERE `employee`.`employee_id` = " . (int) $_POST['employee_id'] . "
LIMIT 1"
Assuming you are using the post method in your form.
You can easily learn how to fetch data from dropdown using this example by clicking Here This repository contains all the codes
I made a form with some dynamic/concatenated select in this way.
FORM HTML (index.php)
<form id="src_form" action="index.php" method="post">
<p>
<select name="catid_1" id="catid_1" class="fieldmax">
<?php echo $cs->show_cat_1(''); ?>
</select>
</p>
<p>
<select name="catid_2" id="catid_2" class="fieldmax">
<option value=""> </option>
</select>
</p>
<p>
<select name="catid_3" id="catid_3" class="fieldmax">
<option value=""> </option>
</select>
</p>
<p>
<input type="submit" name="submit" value="SRC" id="btn_src">
</p>
</form>
AJAX JS
$(function() {
// Ajax post Page
var urlpage = 'ajax-php/con-select.php';
// Vars
var wait = '<option value="">wait</option>';
var all = '<option value="">all</option>';
// Default
$("select#catid_2").prop("disabled", true);
$("select#catid_3").prop("disabled", true);
// CATID_1 Change
$("select#catid_1").change(function(){
// set var
var catid_1 = $("select#catid_1 option:selected").prop("value");
// laod
$("select#catid_2").html(wait);
$.post(urlpage,
{
catid_1:catid_1
},
function(data){
switch (data) {
case all:
$("select#catid_2").html("");
return false;
default:
$("select#catid_2").prop("disabled", false);
$("select#catid_2").html(data);
return false;
}
});
});
// CATID_2 Change ... etc
});
CON-SELECT.PHP
if(isset($_POST['catid_1']))
{
echo $cs->show_cat_2();
die;
}
if(isset($_POST['catid_2']));
{
echo $cs->show_cat_3();
die;
}
CLASS.PHP
public function show_cat_1()
{
$result = $this->db->mysqli->query
("SELECT * FROM cat_1 ORDER BY idcat_1 ASC");
$cat_1 = '<option value="">all</option>';
while($row = $result->fetch_assoc())
{
$cat_1 .= '<option value="' . $row['idcat_1'] . '"';
$cat_1 .= '>' . $row['idcat_1'] . '</option>';
}
return $cat_1;
}
public function show_cat_2()
{
$result = $this->db->mysqli->query
("SELECT * FROM cat_2 ORDER BY idcat_2 ASC");
$cat_2 = '<option value="">all</option>';
while($row = $result->fetch_assoc())
{
$cat_1 .= '<option value="' . $row['idcat_2'] . '"';
$cat_1 .= '>' . $row['idcat_2'] . '</option>';
}
return $cat_2;
}
etc..
my goal is to keep the choices (select value) in fields after submit the form (reload page) while maintaining their functionality. you can do it? how could I do that? thanks
This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
I have a table ("venues") that stores all the possible venues a volunteer can work, each volunteer is assigned to work one venue each.
I want to create a select drop down from the venues table.
Right now I can display the venue each volunteer is assigned, but I want it to display the drop down box, with the venue already selected in the list.
<form action="upd.php?id=7">
<select name="venue_id">
<?php //some sort of loop goes here
print '<option value="'.$row['venue_id'].'">'.$row['venue_name'].'</option>';
//end loop here ?>
</select>
<input type="submit" value="submit" name="submit">
</form>
For example, volunteer with the id of 7, is assigned to venue_id 4
<form action="upd.php?id=7">
<select name="venue_id">
<option value="1">Bagpipe Competition</option>
<option value="2">Band Assistance</option>
<option value="3">Beer/Wine Pouring</option>
<option value="4" selected>Brochure Distribution</option>
<option value="5">Childrens Area</option>
<option value="6">Cleanup</option>
<option value="7">Cultural Center Display</option>
<option value="8">Festival Merch</option>
</select>
<input type="submit" value="submit" name="submit">
</form>
Brochure Distribution option will already be selected when it displays the drop down list, because in the volunteers_2009 table, column venue_id is 4.
I know it will take a form of a for or while loop to pull the list of venues from the venues table
My query is:
$query = "SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort";
How do I populate the select drop down box with the venues (volunteers_2009.venue_id, venues.id) from the venues table and have it pre-select the venue in the list?
$query = "SELECT volunteers_2009.id, volunteers_2009.comments, volunteers_2009.choice1, volunteers_2009.choice2, volunteers_2009.choice3, volunteers_2009.lname, volunteers_2009.fname, volunteers_2009.venue_id, venues.venue_name FROM volunteers_2009 AS volunteers_2009 LEFT OUTER JOIN venues ON (volunteers_2009.venue_id = venues.id) ORDER by $order $sort";
$res = mysql_query($query);
echo "<select name = 'venue'>";
while (($row = mysql_fetch_row($res)) != null)
{
echo "<option value = '{$row['venue_id']}'";
if ($selected_venue_id == $row['venue_id'])
echo "selected = 'selected'";
echo ">{$row['venue_name']}</option>";
}
echo "</select>";
assuming you have an array of venues...personally i don't like to mix the sql with other wizardry.
function displayDropDown($items, $name, $label, $default='') {
if (count($items)) {
echo '<select name="' . $name . '">';
echo '<option value="">' . $label . '</option>';
echo '<option value="">----------</option>';
foreach($items as $item) {
$selected = ($item['id'] == $default) ? ' selected="selected" : '';
echo <option value="' . $item['id'] . '"' . $selected . '>' . $item['name'] . '</option>';
}
echo '</select>';
} else {
echo 'There are no venues';
}
}
<?php
$query = "SELECT * from blogcategory";
//$res = mysql_query($query);
$rows = $db->query($query);
echo "<select name = 'venue'>";
// while (($row = mysql_fetch_row($res)) != null)
while ($record = $db->fetch_array($rows))
{
echo "<option value = '{$record['CategoryId']}'";
if ($CategoryId == $record['CategoryId'])
echo "selected = 'selected'";
echo ">{$record['CategoryName']}</option>";
}
echo "</select>";
?>
<!DOCTYPE html>
<html>
<head>
<title>table binding</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
</head>
<body>
<div id="mydiv" style="width:100px;height:100px;background-color:yellow">
<select id="myselect"></select>
</div>
</body>
</html>
<?php
include('dbconnection.php');
$sql = "SHOW TABLES FROM $dbname";
$result = mysqli_query($conn,$sql);
if (!$result) {
echo "DB Error, could not list tables\n";
echo 'MySQL Error: ' . mysqli_error();
exit;
}
while ($row = mysqli_fetch_row($result)) {
echo "<script>
var z = document.createElement('option');
z.setAttribute('value', '".$row[0]."');
var t = document.createTextNode('".$row[0]."');
z.appendChild(t);
document.getElementById('myselect').appendChild(z);</script>";
}
?>