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
Related
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);
}
}
});
}
I have a select that is echoing out a column (jobTitle) from the database, on change I'm trying to display in another html select, selecting another column (company_name), but only values related to the first html select.
I'm not getting an errors. The first html select value is being passed, but for some reason it's not selecting from the db based on that in the second select.
I'm thinking the issue is with my second sql query.
P.S if anyone knows of a more effective way of doing this i'd be most gratefully to find out.
PHP & HTML:
<select name="jobtitle_select" class="jobtitle_select">
<option class="" name="" value="" >-- Job title --</option>
<?php
$sql = $dbh->prepare("SELECT * FROM jobs_list");
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
while($row = $sql->fetch()) {
$jobTitle = $row['jobTitle'];
echo "<option class='' name='' value='$jobTitle' > $jobTitle </option>";
} // end of while // ?>
</select>
<?php
$jobtitle_select = $_POST['jobtitle_select'];
if ($jobtitle_select){
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE company_name = :jobtitle_select");
$sql->bindParam(':jobtitle_select', $jobtitle_select, PDO::PARAM_STR);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
?>
<select class="company_name_select" >
<option class="" name="" value="" >-- Company name --</option>
<?php while($row = $sql->fetch()) {
$company_name = $row['company_name'];
echo "<option class='' name='' value='$company_name'> $company_name </option>";
} // end of while //
}?> <!-- end of if -->
</select>
JQUERY:
$('.jobtitle_select').change(function(){
$.ajax({
//create an ajax request to load_page.php
type: "POST",
data:$('.jobtitle_select'),
dataType: "html", //expect html to be returned
success: function(date){
$('.company_name_select').html(date);
}
})
});
Your ajax call is not correct, or better say not complete. You need to provide the url, and the posted variable with name and value.
$('.jobtitle_select').change(function(){
$.ajax({
//create an ajax request to load_page.php
url: "load_page.php",
type: "POST",
data: {jobtitle_select: $('.jobtitle_select').val()},
dataType: "html", //expect html to be returned
success: function(date){
$('.company_name_select').html(date);
}
})
});
and your load_page.php file should have the php of code to read data from the database and the html code to display only the inner part of the select:
<?php
$jobtitle_select = $_POST['jobtitle_select'];
if ($jobtitle_select){
$sql = $dbh->prepare("SELECT * FROM jobs_list WHERE company_name = :jobtitle_select");
$sql->bindParam(':jobtitle_select', $jobtitle_select, PDO::PARAM_STR);
if($sql->execute()) {
$sql->setFetchMode(PDO::FETCH_ASSOC);
}
?>
<option class="" name="" value="" >-- Company name --</option>
<?php while($row = $sql->fetch()) {
$company_name = $row['company_name'];
echo "<option class='' name='' value='$company_name'> $company_name </option>";
} // end of while //
}?> <!-- end of if -->
Here is my code, which is having a problem displaying the values of the second:
HTML: my form, the first drop down I get the elements from the database with query.
<form name="farmer" action="index.php" method="post">
<label>
<span>Chose Land:</span>
<select name="land" id="land">
<option value="">--land--</option>
<?php
$sql="SELECT `city` FROM `lands`";
$result =mysql_query($sql);
while ($data=mysql_fetch_assoc($result)){
?>
<option value ="<?php echo $data['city'] ?>" ><?php echo $data['city'] ?></option>
<?php } ?>
</select>
</label>
<label>
<span>Region:</span>
<select name="region" id="region">
<option value="">--region--</option>
</select>
</label>
<input class="button4" type="submit" name="submit" value="Submit" />
</form>
JS
jQuery(document).ready(function() {
jQuery('#land').change(function() {
jQuery.post(
'getList.json.php', {
'land': jQuery('#land').val()
},
function(data, textStatus) {
jQuery('#region').empty();
if(data != null)
{
jQuery.each(data, function(index, value) {
jQuery('#region').append('<option value="' + value + '">' + value + '</option>');
});
}
else {
jQuery('#region').append('<option value="">Please select...</option>');
}
},
'json'
);
});
});
getList.json.php file - Here I make connection between region and land with query(JOIN).
<?php
mysql_connect("localhost", "root", "") or die( "Unable to connect to database");
mysql_select_db("farmer_fields") or die( "Unable to select database");
if($_POST && $_POST['land'] != "") {
$sql="SELECT region FROM regions
LEFT JOIN lands
ON regions.id_lands = lands.id";
$rows = array();
while ($data=mysql_fetch_assoc($sql)){
$rows['region'] = $data;
}
echo json_encode( $rows );
}
?>
No need of json here. You can simply do with jquery and ajax
jquery:
function get_region(country_id) {
if (country_id != 0) {
$("#region_id").html("<option value='0'>Select Region</option>");
$("#region_id").prop("disabled", true);
$.post("ajax/ajax.php", {
country_id: country_id
}, function (data) {
var data_array = data.split(";");
var number_of_name = data_array.length - 1;
var value;
var text;
var opt;
var temp_array;
for (var i = 0; i < number_of_name; i++) {
temp_array = data_array[i].split(",");
value = temp_array[1];
//alert(value);
text = temp_array[0];
opt = new Option(text, value);
$('#region_id').append(opt);
$(opt).text(text);
}
$("#region_id").prop("disabled", false);
});
} else {
$("#region_id").html("<option value='0'>Select Region</option>");
$("#region_id").prop("disabled", true);
}
}
ajax file that is ajax.php
if (isset($_POST["country_id"])) {
$country_id = $_POST["country_id"];
$region_select = mysql_query("select * from region where country_id='$country_id'");
$region = "";
$region_id = "";
while ($region_row = mysql_fetch_array($region_select)) {
$region = $region.$region_row["region"].
",".$region_id.$region_row["id"].
";";
}
echo $region;
}
HTML OF REGION SELECT BOX:
<select name="region_id" id="region_id" disabled="disabled">
<option value="0">Select Region</option>
</select>
You may change mysql_query to PDO for security purpose as mysql_query is depriciated.
Check this, works for me.
JS:
jQuery(document).ready(function() {
var region = jQuery('#region');
var land = jQuery('#land').change(function() {
jQuery.post(
'getList.json.php', {
'land': land.val()
},
function(data) {
jQuery('#region').empty();
if (data != null) {
region.append(data);
}
else {
region.append('<option value="">Please select...</option>');
}
},
'html'
);
});
});
PHP:
if($_POST && $_POST['land'] != "") {
$sql="SELECT region
FROM regions r
LEFT JOIN lands l ON r.id_lands = l.id
WHERE l.city = " . $_POST['land'];
$result = mysql_query($sql); // <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< UPD!
while ($data = mysql_fetch_assoc($result)) {
echo '<option value="' . $data['region'] . '">' . $data['region'] . '</option>';
}
}
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.
I have 2 dropdown lists. The first one shows the regions from a country, the other one every city in the selected state. The problem is that after I submit my form MySQL Database
gets from the first list the ID of the region selected, while the second list doesen't show anything. I want to make my database receive the right information. The name of the region and the name of the city.
How can I do this?
My javascript looks like this:
$(document).ready(function() {
$(".region").change(function() {`enter code here`
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);
}
});
});
});
My section.php script is:
<?php
<label>Country :</label> <select name="country" class="country">
<option selected="selected">--Select Region--</option>
<?php
$sql = mysql_query("SELECT id,region FROM regions ORDER BY region");
while ($row = mysql_fetch_array($sql)) {
$id = $row['id'];
$region = $row['region'];
echo '<option value="' . $id . '">' . $region . '</option>';
}
?>
</select> <br/><br/>
<label>City :</label> <select name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
?>
The ajax_city.php file looks like this:
<?php
if($_POST['id']) {
$id = $_POST['id'];
$sql=mysql_query("SELECT DISTINCT city FROM CITY where id_city=$id order by city");
while($row = mysql_fetch_array($sql)) {
$id=$row['id'];
$data=$row['city'];
echo "<option value=$id>$data</option>";
}
}
?>
The code works fine. But I can't figure out what to do with the database. I think I have to change something in the JavaScript?
Any help please?
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var region = $(this).find('option:selected').html();
$.ajax({
type: "POST",
url: "ajax_city.php",
data: { country: id , name : region },
cache: false,
success: function(html)
{
$(".city").html(html);
$(".city").removeAttr('disabled');
}
});
});
});
</script>
section.php
<label>Country :</label>
<select name="country" class="country">
<option selected="selected">--Select Region--</option>
<?php
$sql=mysql_query("SELECT id,region FROM regions ORDER BY region");
while($row = mysql_fetch_array($sql))
{
$id=$row['id'];
$region=$row['region'];
echo '<option value="'.$id.'">'.$region.'</option>';
}
?>
</select><br/><br/>
<label>City :</label>
<select disabled name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
ajax_city.php
<?php
if($_POST['country'])
{
$id = $_POST['country'];
$region = $_POST['name'];
$sql = mysql_query("SELECT DISTINCT city FROM CITY where id_city = $id order by city");
while($row = mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['city'];
echo "<option value=$id>$data</option>";
}
}
?>
Database: country
CREATE TABLE IF NOT EXISTS `city` ( `id_city` int(11) NOT NULL AUTO_INCREMENT, `city` varchar(30) NOT NULL, `pid` int(11) NOT NULL, PRIMARY KEY (`id_city`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
INSERT INTO `city` (`id_city`, `city`, `pid`) VALUES(1, 'Gujarat', 1),(2, Maharashtra', 1),(3, 'Rajasthan', 1),(4, 'Madhya Pradesh', 1),(5, 'Lahore', 2),(6, 'hyderabad', 2);
CREATE TABLE IF NOT EXISTS `regions` ( `id` int(11) NOT NULL AUTO_INCREMENT, `region` varchar(30) NOT NULL, PRIMARY KEY (`id`)) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=3 ;
INSERT INTO `regions` (`id`, `region`) VALUES(1, 'India'),(2, 'Pakistan');
Javascript On default.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var region = $(this).find('option:selected').html();
$.ajax({
type: "POST",
url: "ajax_city.php",
data: { country: id , name : region },
cache: false,
success: function(html)
{
$(".city").html(html);
$(".city").removeAttr('disabled');
}
});
});
});
</script>
<label>Country :</label>
<select name="country" class="country">
<option selected="selected">--Select Region--</option>
<?php
$conn=mysql_connect("localhost","root","");
$db=mysql_select_db("country",$conn);
$sql=mysql_query("SELECT id,region FROM regions ORDER BY region");
while($row = mysql_fetch_array($sql))
{
$id=$row['id'];
$region=$row['region'];
echo '<option value="'.$id.'">'.$region.'</option>';
}
?>
</select><br/><br/>
<label>City :</label>
<select disabled name="city" class="city">
<option selected="selected">--Select City--</option>
</select>
ajax_city.php
<?php
if($_POST['country'])
{
$conn=mysql_connect("localhost","root","");
$db=mysql_select_db("country",$conn);
$id = $_POST['country'];
$region = $_POST['name'];
$sql = mysql_query("SELECT DISTINCT city FROM CITY where pid = $id order by city");
while($row = mysql_fetch_array($sql))
{
$id=$row['id'];
$data=$row['city'];
echo "<option value=$id>$data</option>";
}
}
?>