Retrieve and display text from multiple dropdown menus without reloading page - php

I am learning PHP, Jquery, Ajax and other web dev languages and have been stuck on this problem for hours on end.
I have two drop-down boxes:
One displaying a list of countries (via a database query)
One displaying a list of cities related to the country chosen (also via a database query)
Anyway, I want to be able to retrieve the text of both menu boxes and use them in further database queries in a text box on the same page at the click of a button but with no reloading of the page involved.
I have used JQuery and Ajax for the dynamic menu so I have some idea of what is required for this task. Here is the code for the page in question:
<body>
<div class = "country">
<label>Select a Country: </label>
<select name="country" onchange="getId(this.value);">
<option value = "">Select Country</option>
<?php
$query = "SELECT DISTINCT(Country) AS Country FROM Locations ORDER BY Country ASC;";
$results = mysqli_query($con, $query);
foreach ($results as $country) {
?>
<option value = "<?php echo $country['Country']; ?>"><?php echo
$country['Country'] ?></option>
<?php
}
?>
</select>
</div>
</br>
<div class="city">
<label>Select a City: </label>
<select name="city" id="cityList">
<option value="">Select a city</option>
</select>
</div>
<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script>
function getId(value){
$.ajax({
type: "POST",
url: "getdata.php",
data: "Country="+value,
success: function(data){
$("#cityList").html(data);
}
});
}
</script>
<button id="button">Go</button>
document.getElementById("button").onclick = function(){
document.getElementById("textbox").innerHTML = "<?php $query = mysqli_query($con, "SELECT * FROM Locations WHERE Country='dropdown text' AND City='dropdown text'");
while($results = mysqli_fetch_array($query)){
echo "Name: " . "$results['City']" . "is in" . "$results['Country']" "</option>";
}
?>";
}
</script>
</body>
The PHP file I have been working on so far is incomplete as I am unsure on how to echo the result, since I want it to eventually end up in the text box on the main page. My PHP is as follows:
<?php
include_once "connection.php";
if(!empty($_POST['Country'])||($_POST['City'])){
$country = $_POST['Country'];
$city = "SELECT * FROM Locations WHERE Country = '$Country' AND City = '$city'";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['Country']; ?>"><?php echo $city['City'] ?></option>
<?php
}
}
?>
Any suggestions or advice would be greatly appreciated.

<?php
include_once "connection.php";
if(!empty($_POST['Country'])){
$country = $_POST['Country'];
$city = "SELECT * FROM Locations WHERE Country = '$Country' ";
$results = mysqli_query($con, $query);
foreach ($results as $city) {
?>
<option value = "<?php echo $city['City']; ?>"><?php echo $city['City'] ?></option>
<?php
}
}
?>
You are posting just 'Country' and have to get just 'country' from post. the city does not come from post.

Related

Populating Second Dropdown Based on first dropdown from the database table without using javascript

I am trying to create a form for the admin of an e-commerce site and the admin should be able to create a category and add new products.
I have two tables in my database from where I want to populate the dropdown list. I want the second dropdown to populate as I select the first drop-down value but I have to do it without the submit button.
This is the code for the form with two drop-downs:-
<form method="post" action="add_category.php">
<h4>Choose the root level:</h4>
<select name="rootLevel">
<?php
$conn = mysqli_connect("localhost","root","","store")
or die("Error in Connection on add_category");
$query = "SELECT * FROM root_category";
$result = mysqli_query($conn,$query) or die("Query failed add_category");
$id=1;
//echo $id;
//echo "Hello";
while($row = mysqli_fetch_assoc($result)){
global $id;
//echo "<h1>$id</h1>";
$id = $row['id'];
echo "<option name='rootLevel' value=$id>".$row['Name']."</option>";
//echo "<option>$id</option>";
}
?>
</select>
<br><br>
<h4>Choose the Level 1 Category:</h4>
<select name="level1">
<?php
global $id;
//echo "<option>".$_POST['rootLevel']."</option>";
$query_level1 = "Select * from level1_category Where P_id = $id";
$result1 = mysqli_query($conn,$query_level1) or die("Query failed level 1");
while($row = mysqli_fetch_assoc($result1)){
$id1 = $row['P_id'];
echo "<option name='level1' value=$id1>".$row['Name']."</option>";
}
?>
</select>
I have successfully populated the first drop-down and now I want to fetch the $id in 'resultValue' without the submit button.
You cant do this only with PHP. You have to use jquery OR Ajax to do this.
Please check this example page . This may help you
https://www.tutorialrepublic.com/faq/populate-state-dropdown-based-on-selection-in-country-dropdown-using-jquery.php
OR
https://www.codexworld.com/dynamic-dependent-select-box-using-jquery-ajax-php/
<head>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "states.php",
data: { country : selectedCountry }
}).done(function(data){
$("#states").html(data);
});
});
});
</script>
</head>
<body>
<div class="form-group">
<label for="country" class="input__label">Country</label>
<select id="country" onchange="states(this.value);" name="country" class="country form-control login_text_field_bg input-style">
<option selected>Choose...</option>
<?php
$sql= $cnn->prepare("SELECT key_iso_code FROM country");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
?>
<option><?php echo $key_iso_code ?></option>
<?php
}
?>
</select>
</div>
<div class="form-group col-md-4">
<label for="inputState" class="input__label">State/Province</label>
<select id="states" name="state" class="form-control input-style">
<option selected>Choose...</option>
</select>
</div>
</body>
<?php
include("PDOConnection.php");
if(isset($_POST["country"])){
// Capture selected country
$country = $_POST["country"];
// Display city dropdown based on country name
if($country !== 'Shoose...'){
$sql= $cnn->prepare("SELECT state.key_name FROM country INNER JOIN state ON country.key_id = state.key_country_id WHERE country.key_iso_code like '$country'");
$sql->execute();
while($i = $sql-> fetch($cnn::FETCH_ASSOC)){
extract($i);
echo "<option>". $key_name . "</option>";
}
}
}
?>

Get value from MySQL database and populate dropdown box [duplicate]

This question already has answers here:
Using PHP to populate a <select></select> dropdown? [duplicate]
(7 answers)
Closed 7 months ago.
I hope someone can help me figure this out as I'm new to PHP and MySQL. But basically, what I'm trying to do is to pull the data from the database and populate the dropdown box and textbox, and so I can update the value in the textbox.
This is the table structure:
id | hf_name | hf_price
------------------------
AI | test 1 | 123
AI | test 2 | 123
So let's say I wanna update "test 1" price, I would select "test 1" in the dropdown selection and update the price in the textbook.
This are my code:
<form class='data_form' action='data/food_update.inc.php' method='post'>
<select>
<?php while ($row = mysqli_fetch_array($result)):; ?>
<option><?php echo $row[1];?></option>
<?php endwhile;?>
</select>
<input type='number' name='hf_price' placeholder='$'>
<button type='submit'>UPDATE</button>
</form>
Include:
<?php
//CONNECTION TO MySQL
include '../dbh.php';
//VARIABLES
$hf_name = $_POST['hf_name'];
$hf_price = $_POST['hf_price'];
$by_user = $_SESSION['Fname'];
$up_date = date('Y-m-d');
$sql = "SELECT hf_name FROM hotfoods";
$result = mysql_query($conn, $sql);
?>
Thanks!
Try changing the option to
<option value="<?php echo $row[2];?>"><?php echo $row[1];?></option>
Where I'm assuming $row[2] variable contains the hf_price value.
$query = "select * from tablename";
$result = mysqli_query($query);
<select>
<?php
while($row = mysqli_fetch_assoc($result){
?>
<option value='<?php echo $row['hf_name']; ?>'><?php echo $row['hf_name']; ?></option>
<?php
}
?>
</select>
but for this you need to change your id datatype into int,
$query = "select * from tablename";
$result = mysqli_query();
<select id="nameID" name="hf_name">
<?php
while($row = mysqli_fetch_assoc($result){
?>
<option value='<?php echo $row['id']; ?>'><?php echo $row['hf_name']; ?></option>
<?php
}
?>
</select>
This will be fine when you fetch details but it does not update any value because for this you need to use Ajax or Jquery for update on Select, let me to try it.
Ajax
$("#nameID").onchange(function(){
var id = $("#id").val();
$.ajax(
url: "update.php",
type: "POST",
data: {'id'=id},
success: function(){
alert("ok");
});
});
Try this it might work.
You should assign a name attribute value (in this case, hf_name) on select element so that that become available in $_POST array.
<form class='data_form' action='data/food_update.inc.php' method='post'>
<select name="hf_name">
<?php while ($row = mysqli_fetch_array($result)):; ?>
<option value="<?php echo $row['hf_name']?>"><?php echo $row['hf_name'];?></option>
<?php endwhile;?>
</select>
<input type='number' name='hf_price' placeholder='$'>
<button type='submit'>UPDATE</button>
</form>
Now this is on which the form will be submitted. Where you can take user's submitted data through $_POST array.
<?php
//CONNECTION TO MySQL
include '../dbh.php';
//VARIABLES
$hf_name = $_POST['hf_name'];
$hf_price = $_POST['hf_price'];
$query = sprintf("UPDATE hotfoods SET hf_price='%d' WHERE hf_name='%s'",
mysql_real_escape_string($hf_price),
mysql_real_escape_string($hf_name));
$result = mysql_query($conn, $query);
if ($result) {
echo 'Price updated!';
} else {
echo 'Problem while updating price';
}
?>

Alternative for huge database list

Ok so I have three tables which contains list World's countries their states and their cities for my registration form. The problem is that the list of the cities is too huge. It contains 48,314 entries in total. So my site is getting hanged and the browser is showing messages to stop script. I am using mozilla for browser purpose.
This is the code I am using to get the cities, states and countries:
$country = "SELECT * FROM countries";
$country = $pdo->prepare($country);
$country->execute();
$state = "SELECT * FROM states";
$state = $pdo->prepare($state);
$state->execute();
$city = "SELECT * FROM cities";
$citq = $pdo->prepare($city);
$citq->execute();
This is my jQuery code:
$(document).ready(function () {
$("#country").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#state option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#state').html('<option value="">Select State</option>').append(options);
});
$("#state").change(function() {
if ($(this).data('options') == undefined) {
$(this).data('options', $('#city option').clone());
}
var id = $(this).val();
var options = $(this).data('options').filter('[value=' + id + ']');
$('#city').html('<option value="">Select City</option>').append(options);
});
});
This is my HTML:
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="state" id="state">
<option value="">Select State</option>
<?php while($j = $state->fetch()){ extract($j); ?>
<option value="<?php echo $country_id; ?>" data="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
<select name="city" id="city">
<option value="">Select City</option>
<?php while($k = $citq->fetch()){ extract($k); ?>
<option value="<?php echo $id ; ?>" data="<?php echo $state_id; ?>"><?php echo $name ; ?></option>
<?php } ?>
</select>
Now can anyone please help me getting a solution as to how I can load it completely smoothly without getting my site hanged whenever the page is refreshed?
You could load the states and cities dynamically once the "parent" selection is made. This would reduce the amount of data.
No clear code because I think you know what you are doing, but the idea:
-> [html] select
-> [js] onChange call php with ajax
-> [php] SQL select states where country="chosencountry"
-> [js] update form/selectbox
EDIT: (code)
JS:
<script>
function BuildSelectbox(job,parent) {
try { req = window.XMLHttpRequest?new XMLHttpRequest():
new ActiveXObject("Microsoft.XMLHTTP");
} catch (e) { /* No AJAX Support */ }
req.open('get','subselects.php?job='+job+'&parent='+parent);
/* let the php echo the resultvalue */
req.onreadystatechange = function() {
handleResponse(div);
};
req.send(null);
}
function handleResponse(div) {
if ((req.readyState == 4) && (req.status == 200)) {
document.getElementById(job).value=req.responseText;
}
}
</script>
PHP part: (subselects.php)
<?
if ($_GET["job"]=="states") {
// assuming there is a key country in states
$state = "SELECT * FROM states where country=".$_GET["parent"];
$state = $pdo->prepare($state);
$state->execute();
} else {
// assuming there is a key state in cities
$city = "SELECT * FROM cities where state=".$_GET["parent"];
$citq = $pdo->prepare($city);
$citq->execute();
}
// echo the whole selectbox
echo '<select id="'.$_GET["job"].'">';
// put the option loop from your queryresult here
echo '</select>';
?>
HTML:
<div id="countries" onChange="BuildSelectbox('states',this.selectedIndex);>
<select name="country" id="country">
<option value="">Select Country</option>
<?php while($i = $country->fetch()){ extract($i); ?>
<option value="<?php echo $id; ?>"><?php echo $name; ?></option>
<?php } ?>
</select>
</div>
<div id="states"></div>
<div id="cities"></div>
This dynamically generates full selectboxes and puts them into the empty divs "states and "cities". Of course you need to output the selectbox in the php code. Parent of states is country and parent of cities is states. Hope this explains it.

PHP/MySQL dropdowns

I have a main MySQL table called restaurants which holds all details for each restaurant - RestaurantID, RestaurantName, Address, Town, County etc.
I am creating a Review and ratings form in PHP to allow my users to review each of the restaurants. I have created 2 dropdown menus one which the user will select the County and the second I hope to populate with RestaurantName of those in that County.
Can anyone spot where I am going wrong? My first dropdown populates without any issues, although the second dropdown is blank?
I've added all my code so far for this, anything else that you think would be useful let me know.
leave.php
<?php
include_once "settings.php"
?>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<body>
<div class="County">
<label>County</label>
<select name = "County" onchange="getId(this.value);">
<option value ="">Select County </option>
<?php
$query = "SELECT DISTINCT County FROM restaurants";
$results = mysqli_query($con, $query);
foreach ($results as $restaurants) {
?>
<option value ="<?php echo $restaurants['County']; ?>"><?php echo $restaurants["County"]; ?></option>
<?php
}
?>
</select>
</div>
<div class="RestName">
<label>Restaurant</label>
<select name = "Restaurant" id="RestList">
<option value ="">Select Restaurant </option>
<option value="" >
<?php
include_once "settings.php";
if (!empty($_POST["RestaurantID"])) {
$RestaurantID = $_POST["RestaurantID"];
$query = "SELECT * FROM restaurants WHERE RestaurantID = $RestaurantID";
$results = mysqli_query($con, $query);
foreach ($results as $County) {
?>
<option value="<?php echo $restaurants["RestaurantID"]; ?>"><?php echo $restaurants["RestaurantName"]; ?>"></option>
<?php
}
}
?>
</select>
</div>
<script>
function getId(val){
$.ajax({
type: "POST",
url:"getdata.php",
data: "RestaurantID="+val,
success: function(data){
$("#RestList").html(data);
}
});
}
</script>
</body>
</html>
getdata.php
<?php
include_once "settings.php";
if (!empty($_POST["RestaurantID"])) {
$RestaurantID = $_POST["RestaurantID"];
$query = "SELECT * FROM restaurants WHERE RestaurantID = $RestaurantID";
$results =
($con, $query);
foreach ($results as $restaurants) {
?>
<option value="<?php echo $restaurants['RestaurantID']; ?>"><?php echo $restaurants["RestaurantName"]; ?>"></option>
<?php
}
}
?>
In this line:
<select name="Restaurant" id="RestList" </select>
You don't actually close the "<select>" tag...

i am trying to display productname from newproduct mysql table into combobox. The following code is executing but its displaying a blank

**<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while($result = mysql_fetch_assoc($query_result))
{
?>
<option value = "<?php echo $result['productname']?>"><?php echo $result['productname']?></option>
//the above code displays the combo box with one empty space as output.
**
change fetch records using mysql_fetch_array()
while($result = mysql_fetch_array($query_result))
{
*********
}
And try it..
Try this
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
$query_result = mysql_query($category);
while($result = mysql_fetch_array($query_result))
{
?>
<option value = "<?php echo $result['productname']; ?>"><?php echo $result['productname']; ?></option>
<?php
}
?>
</select>
try this:
<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while($result = mysql_fetch_array($query_result))
{
?>
<option value = "<?php echo $result['productname']?>"><?php echo $result['productname']?></option>
Your while loop is being fully executed in the first <?php ... ?> snippet. The syntax you used for your while loop will not execute across multiple php code snippets.
Try echoing out your option HTML code and thus having only one php code snippet.
<html>
<body>
<form name="call">
<select name="category">
<option>Select a category</option>
<?php
mysql_connect("localhost","root","");
mysql_select_db("shenvel");
$category = "SELECT productname FROM newproduct";
//retrieving product name alone from newproduct
$query_result = mysql_query($category);
while ($result = mysql_fetch_assoc($query_result)) {
echo '<option value = "', $result['productname'], '">', $result['productname'], '</option>';
}
?>

Categories