So i want to make my select dropdown box flexible, however i tried using AJAX which i found online, but the AJAX request is a standalone data, it does not return back the data.
Is there any convenient way to get the data and able to submit to another PHP file ?
Here is my Code
index.php
<td>
<select id="ownerID" name="OwnerID" class="id" required>
<?php
$Employee_ID='';
$sql1="SELECT Employee_ID FROM user1 WHERE Position1='QE' OR Position1='OTHER'";
$result1=odbc_exec($conn,$sql1);?>
<option value="">Choose</option>
<?php while($row1=odbc_fetch_array($result1)){
$Employee_ID=$row1['Employee_ID'];
?>
<option value ="<?php echo $Employee_ID;?>"><?php echo $Employee_ID;?></option>
<?php
}
?>
</select>
</td>
</tr>
<tr>
<td id="response" style="margin-left:50px;">
</td>
AJAX
<script type="text/javascript">
$(document).ready(function(){
$("select.id").change(function(){
$("#response option").remove();
var selectedOwner = $(".id option:selected").val();
$.ajax({
type: "POST",
url: "process-request.php",
data: { id : selectedOwner}
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
post-requst.php
if(isset($_POST["id"])){
$id = $_POST["id"];
$Form_Tracking_ID=null;
$sql="SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 IS NULL AND CEF_ID IS NULL
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 IS NULL AND CEF_ID = ' '
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 = ' ' AND CEF_ID IS NULL
UNION SELECT Form_Tracking_ID FROM masterlist1 WHERE Owner_I_Employee_ID = '$id' AND Tool_Status='Active' AND Dereg_Reason1 = ' ' AND CEF_ID = ' '";
$result=odbc_exec($conn,$sql);
if($id !== 'Choose'){
echo "<label>Tool ID:</label>";
echo "<br><select id='toolid' name='ownerid' required>"; ?>
<option value="">Choose</option>
<?php while($row=odbc_fetch_array($result)){
$search=$row['Form_Tracking_ID']; ?>
<option value="<?php echo $search ?>"><?php echo $search ?></option>
<?php }
echo "</select>";
}
}
You can use a function for get data from database, getting value of 1º select and put them on 2º select
//Get value from 1 select
$("#firstSelect").change(function () {
let firstSelectValue = $("#firstSelect").val();
$("#secondSelect").text("");
//Calling a function to get value from database
getDataForSecondSelect(firstSelectId);
})
function getDataForSecondSelect(firstSelectValue) {
$.ajax({
url: `getDataForSecondSelect.php?value=${firstSelectValue}`,
method: "GET",
dataType: "JSON",
success: function (message) {
if (message.length != 0) {
$('#secondSelect').prop('disabled', false);
for (let i = 0; i <= message.length; i++) {
$("#secondSelect").prepend(`<option value=${message[i]["id"]}>${message[i]["name"]}</option>`);
}
} else {
$("#subcategoriaProduto").text("");
$("#subcategoriaProduto").prepend("<option>There's no data</option>");
$('#subcategoriaProduto').prop('disabled', true);
}
}
});
}
Here i am selecting company name as an option
Here i need to show relevant categories under company name;
How can i do this?
You can do that by using Jquery and Ajax. This is a simple code snippet to achieve what you want.
First, inside your index.php:
<script
type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
$(".company").change(function(){
var company = $(this).val();
var dataString = 'company=' + company;
$.ajax({
type: "POST",
url: "business.php",
// You can edit choice2.php for other filename you want
data: dataString,
cache: false,
success: function(html){
$(".business").html(html);
}
});
});
});
</script>
Company :
<select name="company" class="company">
<option selected="selected">--Select Company--</option>
<?php
include('db.php');
$sql= "SELECT Company FROM table_test";
// You should edit table_test for your table name
$result = mysqli_query($con ,$sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$company = $row['Company'];
echo '<option value="'.$company.'">'.$company.'</option>';
}
?>
</select>
<br/><br/>
Business :
<select name="business" class="business">
<option selected="selected">--Select Business--</option>
</select>
Then inside your second file. I called it business.php:
<?php
include('db.php');
if($_POST['company']){
$company = $_POST['company'];
$sql= "SELECT Business FROM table_test WHERE Company='$company'";
$result = mysqli_query($con ,$sql);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
$business = $row['Business'];
echo '<option value="'.$business.'">'.$business.'</option>';
}
}
?>
Then to connect to the database you can use this code snippet. I called this file db.php.
<?php
$con = mysqli_connect("localhost","root","","database_test");
// You should edit database_test with your database name
if (mysqli_connect_errno()){
echo "Failed to connect to MySQL: ".mysqli_connect_error();
}
?>
I want to know how I can link three dropdown lists together. I want to let user select the country, then select the state and then select the city. Actually I tried multiple methods but What I have done is as bellow:
<div class="row">
<div class="col-sm-4"><div class="form-group">
<label for="countries">Country</label>
<select class="form-control" id="countries">
<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "countries";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM countries";
$result = $conn->query($sql);
//echo "<select id='countries'>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
//echo "</select>";
$conn->close();?>
</select>
</div></div>
<div class="col-sm-4"><div class="form-group">
<label for="countries">State</label>
<select class="form-control" id="states">
<?php
$servername = "localhost";
$username = "root";
$password = "123";
$dbname = "countries";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
if($_POST['submit'] && $_POST['submit'] != 0)
{
$countries=$_POST['countries'];
}
//echo "Connected successfully";
$sql = "SELECT * FROM regions where country_id = $countries";
$result = $conn->query($sql);
//echo "<select id='states'>";
while ($row = $result->fetch_assoc()) {
echo "<option value='" . $row['name'] . "'>" . $row['name'] . "</option>";
}
//echo "</select>";
$conn->close();?>
</select>
</div></div>
</div>
What I need to do is to make three dropdown lists (2 of them are shown above) to let the users select country first, then the second dropdown shows the states/regions based on user selection and finally select city based on selected state.Please show me the solution to do this.
I had written the code for this sometime last year, what you need is to use ajax, have on change event.
Please not I had written my solution using PDO I know yours requires mysqli, but however I don't have much of a time to re write the whole
thing to mysqli
But I hope you will see the logic on how to do this and hopefully you will be able to convert it to mysqli by yourself with no hustle.
my index file
<script src="jquery.min.js"></script>
<?php require 'db_config.php';?>
<script type="text/javascript">
$('#country').on('change', function() {
var countryID = $(this).val();
if (countryID) {
$.ajax({
type: 'POST',
url: 'locations.php',
data: 'country_id=' + countryID,
success: function(html) {
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
}
});
} else {
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
$(this).remove('has-errors');
});
$('#state').on('change', function() {
var stateID = $(this).val();
if (stateID) {
$.ajax({
type: 'POST',
url: 'locations.php',
data: 'state=' + stateID,
success: function(html) {
$('#city').html(html);
}
});
} else {
$('#city').html('<option value="">Select city first</option>');
}
});
</script>
<form method="POST" action="" id="reg_form">
<select name="country" id="country" class="input">
<option value="0">Select country</option>
<?php
$stmt= $dbh->Prepare("SELECT countryID, countryName FROM countries ORDER BY countryName ASC");
$stmt->execute();
$results= $stmt->Fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
foreach($results as $row){
echo '<option value="'.$row['countryID'].'">'.$row['countryName'].'</option>';
}
}else{
echo '<option value="">country not available</option>';
}
?>
</select>
<select name="state" id="state" class="input">
<option value="">Select country first</option>
</select>
<select name="city" id="city" class="input">
<option value="">Select state first</option>
</select>
</form>
locations.php
<?php
/**
* Created by PhpStorm.
* User: Masivuye
* Date: 2016/12/19
* Time: 11:27 AM
*/
require 'db_config.php';
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
$sql=$dbh->prepare("SELECT DISTINCT states.stateID,states.stateName from states INNER JOIN countries ON states.countryID = ? ");
$sql->bindValue(1,$_POST['country_id']);
$sql->execute();
$results =$sql->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
echo '<option value="0">Select state</option>';
foreach($results as $row){
echo '<option value="'.$row['stateID'].'">'.$row['stateName'].'</option>';
}
}else{
echo '<option value="">state not available</option>';
}
}
if(isset($_POST["state"]) && !empty($_POST["state"])){
$sql=$dbh->prepare("SELECT DISTINCT cities.cityID,cities.cityName,cities.stateID from cities INNER JOIN states ON cities.stateID= ? ");
$sql->bindValue(1,$_POST['state']);
$sql->execute();
$results =$sql->fetchall(PDO::FETCH_ASSOC);
if(count($results) > 0){
echo '<option value="0">Select City</option>';
foreach($results as $row){
echo '<option value="'.$row['cityID'].'">'.$row['cityName'].'</option>';
}
}else{
echo '<option value="">city not available</option>';
}
}
?>
db_config.php
<?php
$servername = "localhost";
$username = "hidden";
$password = "hidden";
$dbname = "mytestDB";
try {
$dbh= new PDO("mysql:host=$servername;dbname=$dbname",$username,$password);
$dbh->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo "Could not connect".$e->getMessage();
error_log($e);
}
?>
my tables
CREATE TABLE IF NOT EXISTS `states` (
`stateID` int(6) NOT NULL AUTO_INCREMENT,
`stateName` varchar(255) NOT NULL,
`countryID` int(6) NOT NULL,
PRIMARY KEY (`stateID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `states`
--
INSERT INTO `states` (`stateID`, `stateName`, `countryID`) VALUES
(3, 'Western Cape', 2),
(4, 'Eastern Cape', 1),
(5, 'North West', 2),
(6, 'Northen Cape', 2);
--
-- Table structure for table `cities`
--
CREATE TABLE IF NOT EXISTS `cities` (
`cityID` int(6) NOT NULL AUTO_INCREMENT,
`cityName` varchar(255) NOT NULL,
`stateID` int(6) NOT NULL,
PRIMARY KEY (`cityID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
--
-- Dumping data for table `cities`
--
INSERT INTO `cities` (`cityID`, `cityName`, `stateID`) VALUES
(1, 'Cape Town', 3),
(2, 'East London', 4);
-- --------------------------------------------------------
--
-- Table structure for table `countries`
--
CREATE TABLE IF NOT EXISTS `countries` (
`countryID` int(6) NOT NULL AUTO_INCREMENT,
`countryName` varchar(255) NOT NULL,
PRIMARY KEY (`countryID`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 ;
--
-- Dumping data for table `countries`
--
INSERT INTO `countries` (`countryID`, `countryName`) VALUES
(1, 'South Africa'),
(2, 'Zambia'),
(3, 'Zimbabwe '),
(4, 'Uganda'),
(5, 'USA'),
(6, 'Brazil'),
(7, 'India'),
(8, 'Austrilia'),
(9, 'Ghana');
-- --------------------------------------------------------
NB: use your own characterset on the tables, you may use utf-8
Hope this will point you to the correct direction, hoping also other SO users will help where I missed something.
You can achieve what you want a multiple ways, but you have to make many improvements on your code.
For eg. you could just make connection on top of your script rather than multiple times (wherever you need). Also you could fetch the data from database tables on top of your script like this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM countries";
$result = $conn->query($sql);
$countries = $result->fetch_all(MYSQLI_ASSOC);
$sql = "SELECT * FROM regions";
$result = $conn->query($sql);
$regions = $result->fetch_all(MYSQLI_ASSOC);
?>
Then add your html codes below.
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="countries">Country</label>
<select class="form-control" id="countries" onchange="refreshPage(this)">
<option value=""> Select Country</option>
<?php foreach($countries as $country): ?>
<option value="<?= $country['id'] ?>" ><?= $country['name'] ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="regions">Region</label>
<select class="form-control" id="regions">
<option value=""> Select Region</option>
<?php foreach($regions as $region): ?>
<option value="<?= $region['id'] ?>"><?= $region['name'] ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
You want the countries and regions related, for which you can use javascript or even jQuery (if you want) to fetch regions separately. Or just refresh the page when country is selected, like. (Mind the refreshPage() Method on countries select box above. )
<script>
function refreshPage(object)
{
var country_id = object.options[object.selectedIndex].value;
if (country_id != '') {
window.location.href = '?country_id='+country_id;
}
}
</script>
Now you have to just take the country_id value from $_GET to filter regions. The complete code looks like this.
<?php
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "test";
$conn = new mysqli($servername, $username, $password, $dbname);
$sql = "SELECT * FROM countries";
$result = $conn->query($sql);
$countries = $result->fetch_all(MYSQLI_ASSOC);
$where = "";
if (isset($_GET['country_id']) && $_GET['country_id'] != '') {
$where = " WHERE country_id = '{$_GET['country_id']}'";
}
$sql = "SELECT * FROM regions {$where}";
$result = $conn->query($sql);
$regions = $result->fetch_all(MYSQLI_ASSOC);
?>
<div class="row">
<div class="col-sm-4">
<div class="form-group">
<label for="countries">Country</label>
<select class="form-control" id="countries" onchange="refreshPage(this)">
<option value=""> Select Country</option>
<?php foreach($countries as $country): ?>
<option value="<?= $country['id'] ?>" <?php echo isset($_GET['country_id']) && $_GET['country_id'] == $country['id'] ? 'selected' : ''; ?> ><?= $country['name'] ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label for="regions">Region</label>
<select class="form-control" id="regions">
<option value=""> Select Region</option>
<?php foreach($regions as $region): ?>
<option value="<?= $region['id'] ?>"><?= $region['name'] ?></option>
<?php endforeach; ?>
</select>
</div>
</div>
</div>
<script>
function refreshPage(object)
{
var country_id = object.options[object.selectedIndex].value;
if (country_id != '') {
window.location.href = '?country_id='+country_id;
}
}
</script>
The main problem with this code is that, it is not preventing any SQL injection and is vulnerable in many ways. You have to use PDO instead of mysqli and use prepared statement to filter the regions.
In this case you should use AJAX. Onchange (select) you can send a xmlhttprequest (JS) to a separate php file, which returns the data you need (for example as JSON), and insert it into your website with JS.
Example:
<script type="text/javascript">
function filtern()
{
region = document.getElementById("feld1").value;
xhr = new XMLHttpRequest();
xhr.onreadystatechange = function()
{
if(xhr.readyState==4 && xhr.status==200)
{
filtered_region = JSON.parse(xhr.responseText);
document.getElementById("select1").innerHTML = "";
for(i=0;i<filtered_region.length;i++)
{
document.getElementById("select1").innerHTML += "<option>"+filtered_region[i]+"</option>";
}
}
}
xhr.open("GET","get_your_data.php?region="+region,true);
xhr.send();
}
</script>
<form>
<p>Feld1: <input type="text" name="feld1" id="feld1" onchange="filtern()" /></p>
<select name="select1" id="select1"></select>
</form>
get_your_data.php returns the data you want to display.
I got 3 drop down boxes dependent on each other when selected. For e.g. if I select a type from drop down 1, then drop down 2 populates only the options relevant to what i select from the first drop down box. The 3rd drop down is dependable on the 2nd drop down option.
The problem i am facing is that the options on the drop down boxes are not refreshing when i want to choose something different.
Can anyone help me?
This is my form:
<label>Tour Type </label>
<select id="tourtype" name="tourtype" required>
<option value="" selected="selected">--Select--</option>
<?php
$sql=mysql_query("Select tour_type_id,tour_name from tour_type");
while($row=mysql_fetch_array($sql))
{
$tour_type_id=$row['tour_type_id'];
$name=$row['tour_name'];
echo "<option value='$tour_type_id'>$name</option>";
}
?>
</select>
<label>Country</label>
<select id="country" name="country" class="country" required>
<option value="" selected="selected">-- Select --</option>
</select>
<label>Destination</label>
<select id="destination" name="destination" class="destination" required>
<option value="" selected="selected">-- Select --</option>
</select>
This is the js at the bottom of the form:
<script>
$('#tourtype').change(function () {
var id = $(this).val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {
id: id,
get_countries: 1
},
success: function (html) {
$("#country").empty();
$("#country").append(html);
},
error: function () {
alert("ajax failed");
}
});
});
$('#country').change(function () {
var id = $(this).val();
$.ajax({
type: "POST",
url: "ajax.php",
data: {
id: id,
get_destination: 1
},
success: function (html) {
$("#destination").empty();
$("#destination").append(html);
},
error: function () {
alert("ajax failed");
}
});
});
</script>
Finally this is the ajax.php
<?php
include('../config.php');
if ($_REQUEST['get_countries']) {
$sql = mysql_query("SELECT * FROM `countries` WHERE `tour_type_id`=" . $_REQUEST['id']);
$countries = "";
while ($row = mysql_fetch_array($sql)) {
$cid = $row['countries_id'];
$name = $row['countries_name'];
$countries .= "<option value='" . $cid . "'>" . $name . "</option>";
}
echo $countries;
} elseif ($_REQUEST['get_destination']) {
$destination = "";
$sql = mysql_query("SELECT * FROM `destination` where `country_id` =" . $_REQUEST['id']);
while ($row = mysql_fetch_array($sql)) {
$destination_id = $row['destination_id'];
$name = $row['destination_name'];
$destination .= "<option value='" . $destination_id . "'>" . $name . "</option>";
}
echo $destination;
}
?>
I have fixed the problem. Just had to add more data to the 3 separate tables where my query is fetching the data from
I've a html form where the countries in the drop down are coming from a database. If user selects any country, then the city drop diwn will appear based on selected country.
If user wrongly input any field of the form (there are other field in this form) then country drop down will will remember which country the user initially selected, but clears the city, resetting it to --Select City--. I'm trying to selected the city name but I can't. Any idea ?
Ajax Code here:
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});
});
});
</script>
ajax_city.php here
<?php
require_once("toplevel/content/database/databd.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("select Name from cities WHERE CountryCode ='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['Code'];
$data=$row['Name'];
if($_POST['city'] == $data)
{
$sel = 'selected = "selected"';
}
else
{
$sel = " ";
}
echo '<option value="'.$data.'" ' .$sel . ' >'.$data.'</option>';
}
}
?>
Html form here:
<tr>
<td>PAYS <span style="color: #FF0000;">*</span></td>
<td>
<select name="country" class="country">
<option value="">Select</option>
<?php
$sql=mysql_query("select * from country");
while($row=mysql_fetch_array($sql))
{
$id=$row['Code'];
$data=$row['Name'];
$data = mb_convert_encoding($data, 'UTF-8');
if($id == $_POST['country'])
{
$sel = 'selected="selected"';
}
else
{
$sel = "";
}
echo '<option value="'.$id.'"' . $sel . '>'.$data.'</option>';
}
?>
</select>
</td>
</tr>
<tr>
<td>City</td>
<td>
<select class="city" name="city">
<option selected="selected" value="">--Select City--</option>
</select>
</td>
</tr>
Not quite sure but issue is in datastring try changing this:
$(".country").change(function(){
var id=$(this).val();
var dataString = {'id': id};
$.ajax({
type: "POST",
url: "ajax_city.php",
data: dataString,
cache: false,
success: function(html){
$(".city").html(html);
}
});
});
You will need to rebuild your HTML on reload, but now with your City list (this is untested, but based on your code from the Country dropdown):
<tr>
<td>City</td>
<td>
<select class="city" name="city">
<option selected="selected" value="">--Select City--</option>
<?php
if (isset($_POST['city']) {
$sql=mysql_query("select * from city");
while($row=mysql_fetch_array($sql))
{
$id=$row['Code'];
$data=$row['Name'];
$data = mb_convert_encoding($data, 'UTF-8');
if($id == $_POST['city']) { $sel = 'selected="selected"'; }
else { $sel = ""; }
echo '<option value="'.$id.'"' . $sel . '>'.$data.'</option>';
}
}
?>
</select>
</td>
</tr>
WARNING: This is just same sample code. This should never ever go into production, because it has the potential for being extremely unsafe! As #PolishPrince has pointed out above, you should at least use PDO or MySQLi.