I am having significant issues trying to get the AJAX to fire on this PHP code.
I can get the first field populated without issue, however the AJAX call does not seem to populate the first dependency (and therefore the second). I am an AJAX newbie (and have googled extensively) but cannot seem to crack this one.
Note that the ladb.php file runs fine.
<?php
// Include the database config file
include_once 'ladb.php';
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body style="background: #D5DDE0">
<div class="container">
<form action="" method="post">
<div class="form-group col-md-6">
<!-- Country dropdown -->
<label for="country">Country</label>
<select class="form-control" id="country">
<option value="">Select Country</option>
<?php
$query = "SELECT * FROM City_Index GROUP BY country ORDER BY country ASC";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo "<option value='{$row["countryid"]}'>{$row['country']}</option>";
}
}else{
echo "<option value=''>Country not available</option>";
}
?>
</select><br>
<!-- State dropdown -->
<label for="admin">Administrative Area</label>
<select class="form-control" id="admin">
<option value="">Select Administrative Area</option>
</select><br>
<!-- City dropdown -->
<label for="city">city_ascii</label>
<select class="form-control" id="city">
<option value="">Select City</option>
</select>
</div>
</form>
</div>
</body>
</html>
<script type="text/javascript">
$(document).ready(function(){
// Country dependent ajax
$("#country").on("change",function(){
var country = $(this).val();
if (countryid) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{countryid:countryid},
success:function(data){
$("#admin").html(data);
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
}else{
$('#admin').html('<option value="">Select Country</option>');
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
// state dependent ajax
$("#admin").on("change", function(){
var admin = $(this).val();
if (admin) {
$.ajax({
url :"action.php",
type:"POST",
cache:false,
data:{admin:admin},
success:function(data){
$("#city").html(data);
}
});
}else{
$('#city').html('<option value="">Select Administrative Area</option>');
}
});
});
</script>
The action.php file below
<?php
// Include the database config file
include_once 'ladb.php';
// Get country id through state name
$country = $_POST['country'];
if (!empty($country)) {
// Fetch state name base on country id
$query = "SELECT * FROM CityList WHERE country = {$country} GROUP BY admin_name_ascii";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['admin_id'].'">'.$row['admin_name_ascii'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif (!empty($_POST['admin'])) {
$admin = $_POST['admin'];
// Fetch city name base on state id
$query = "SELECT * FROM CityList WHERE admin_id = {$admin}";
$result = $ladb->query($query);
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
echo '<option value="'.$row['cityid'].'">'.$row['city_ascii'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
Any help greatly appreciated!
Thanks to #zergski I note that one of references were defined (countryid in Line 53). DevTools is my new best friend.
Related
I have 2 SelectOption where if Select 1 is selected, then Select 2 automatically synchronizes with Select 1
all SelectOptions contents retrieve from a database table.
SELECT 1 & 2 scripts:
<select name="leavetype" autocomplete="off">
<option value="">Choose Leave Type</option>
<?php $sql = "SELECT LeaveType from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->LeaveType);?>"><?php echo htmlentities($result->LeaveType);?></option>
<?php }} ?>
</select>
<select name="rightsgranted" autocomplete="off">
<option value="">Rights Granted</option>
<?php $sql = "SELECT RightsGranted from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option value="<?php echo htmlentities($result->RightsGranted);?>"><?php echo htmlentities($result->RightsGranted);?></option>
<?php }} ?>
</select>
example
you need to use ajax for this work
this example is for the select city of a state
index.php
<?php
//Include the database configuration file
include 'dbConfig.php';
//Fetch all the country data
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select id="country">
<option value="">Select Country</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['country_id'].'">'.$row['country_name'].'</option>';
}
}else{
echo '<option value="">Country not available</option>';
}
?>
</select>
<select id="state">
<option value="">Select country first</option>
</select>
<select id="city">
<option value="">Select state first</option>
</select>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.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>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
<select id="state">
<option value="">Select country first</option>
</select>
<select id="city">
<option value="">Select state first</option>
</select>
ajax.php
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
var countryID = $(this).val();
if(countryID){
$.ajax({
type:'POST',
url:'ajaxData.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>');
}
});
$('#state').on('change',function(){
var stateID = $(this).val();
if(stateID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'state_id='+stateID,
success:function(html){
$('#city').html(html);
}
});
}else{
$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
ajaxData.php
<?php
//Include the database configuration file
include 'dbConfig.php';
if(!empty($_POST["country_id"])){
//Fetch all state data
$query = $db->query("SELECT * FROM states WHERE country_id = ".$_POST['country_id']." AND status = 1 ORDER BY state_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//State option list
if($rowCount > 0){
echo '<option value="">Select state</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['state_id'].'">'.$row['state_name'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}elseif(!empty($_POST["state_id"])){
//Fetch all city data
$query = $db->query("SELECT * FROM cities WHERE state_id = ".$_POST['state_id']." AND status = 1 ORDER BY city_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
//City option list
if($rowCount > 0){
echo '<option value="">Select city</option>';
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['city_id'].'">'.$row['city_name'].'</option>';
}
}else{
echo '<option value="">City not available</option>';
}
}
?>
see the full tutorial in this link
I Found simple method.
This might not be the best solution, but it should do the trick.
Maybe this will help others: http://jsfiddle.net/7BUmG/3876/
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$('#leavetype').change(function() {
var rightsgranted = $(this).find("option:selected").attr("title");
$('#RightsGranted').val(rightsgranted);
});
});
</script>
<select id="leavetype" name="leavetype" autocomplete="off">
<option value="">Choose Leave Type</option>
<?php $sql = "SELECT LeaveType,RightsGranted from tblleavetype";
$query = $dbh -> prepare($sql);
$query->execute();
$results=$query->fetchAll(PDO::FETCH_OBJ);
$cnt=1;
if($query->rowCount() > 0)
{
foreach($results as $result)
{ ?>
<option title="<?php echo htmlentities($result->RightsGranted);?>" value="<?php echo htmlentities($result->LeaveType);?>"><?php echo htmlentities($result->LeaveType);?></option>
<?php }} ?>
</select>
<input type='text' name="RightsGranted" id="RightsGranted" hidden/>
I am trying to pass a value of a select option input using Ajax into another page PHP and get the database and fetch data into select option. However, my problem is there is nothing to show in second select option.
I have the select option called Country which contains Country 1, Country 2, Country 3, Country 4 with cid 1,2,3,4.
what I wanted is past Country ID (cid) into getdata.php and query the database of City which contains City a, city b, city c, etc. and fetch city's data into select option using Ajax.
I need to make city select option dynamically change when I select the country.
here is my database structure :
Country.db
City.db
Here is my script :
dropdown.php
<?php
require_once "connection.php";
?>
<html>
<head>
<title>Dropdown ajax</title>
</head>
<body>
<div class="country" >
<label>Country</label>
<select name="country" onchange="getId(this.value);">
<option value=""> -- Select Country -- </option>
<!-- populate value using php -->
<?php
$query = "SELECT * FROM country";
$result = mysqli_query($con,$query);
//loop
foreach ($result as $country) {
?>
<option value="<?php echo $country["cid"]; ?>"> <?php echo $country["country"]; ?> </option>
<?php
}
?>
</select>
</div>
<div class="city">
<label>City</label>
<select name="city" id="cityList">
<option value=""></option>
</select>
</div>
<script src="jquery-3.2.1.min"></script>
<script type="text/javascript">
function getId(val){
// ajax function
$.ajax({
type:"POST",
url:"getdata.php",
data:"cid="+val,
success:function(data){
$(#cityList).html(data);
}
});
}
</script>
</body>
</html>
from the dropdown, I am trying to past cid into getdata.php using ajax and fetch the database into select option inside drop-down.php
getdata.php
<?php
require_once "connection.php";
if(!empty($_POST["cid"])){
$cid = $_POST["cid"];
$query = "SELECT * FROM city WHERE cid = $cid";
$result = mysqli_query($con,$query);
foreach ($result as $city) {
?>
<option value="<?php echo $city["cityId"];?>"><?php echo $city["city"];?></option>
<?php
}
}
?>
here is my connection.php
<?php
$con = mysqli_connect("localhost","root","admin","dropdowndb");
//check connection
if(mysqli_connect_errno()){
echo "Failed to connect :".mysqli_connect_errno();
}
?>
the result is like this :
so how to fix this problem?
The selector inside the ajax success handler must be a string, not identifier:
success:function(data){
$('#cityList').html(data);
}
So I'm a total beginner and I'm working on a project to create dynamic dropdown forms. I have written some code and am wondering now if I can insert php & html inside a multi line php variable. This code below is what I just tried[javascript not included here] but php shows error. Is this not possible at all or is it some error on my part? Thanks in advance.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<?php
$chooseroom=<<<HERE
<div class="select-boxes">
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
?>
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?php
if($rowCount > 0){
while($row = $query->fetch_assoc()){
echo '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
}else{
echo '<option value="">occupation not available</option>';
}
?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
HERE;
echo $chooseroom;
</body>
</html>
OK AS REQUESTED BY SOME OF YOU HERE IS MY JAVASCRIPT:
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#occupation').on('change',function(){
var occupationID = $(this).val();
if(occupationID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'occupation_id='+occupationID,
success:function(html){
$('#specification').html(html);
$('#expertise').html('<option value="">Select specification first</option>');
}
});
}else{
$('#specification').html('<option value="">Select occupation first</option>');
$('#expertise').html('<option value="">Select specification first</option>');
}
});
$('#specification').on('change',function(){
var specificationID = $(this).val();
if(specificationID){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'specification_id='+specificationID,
success:function(html){
$('#expertise').html(html);
}
});
}else{
$('#expertise').html('<option value="">Select specification first</option>');
}
});
});
</script>
Yes it is possible to add multi line html and php to a variable. You can add multiple entries in options as given below
while($row = $query->fetch_assoc()){
/* here . operator is used to append
to the existing value of $chooseroom */
$chooseroom .= '<option value="'.$row['occupatio_id'].'">'.$row['occpation_name'].'</option>';
}
Print this variable where it is required as
<?php echo $chooseroom; ?>
You can't do what you're attempting in the way you're attempting it; what you're trying to do is run PHP code inside a HEREDOC block.
However, you can put the PHP code, and create your set of options, before that block and just interpolate it where required (you don't even need to assign the HEREDOC block to a variable, you can use echo it out):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
// Create an HTML options string
$htmlOptions = "";
if($rowCount > 0) {
while($row = $query->fetch_assoc()){
$htmlOptions .= '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
$htmlOptions .= '<option value="">occupation not available</option>';
}
// Output
echo <<<HERE
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
$htmlOptions
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
HERE;
?>
</body>
</html>
Though, to be honest, the whole HEREDOC thing is slightly superfluous here as you can just break out of the PHP and echo out your options where you need them - makes for slightly better separation between the PHP and HTML code as well:
<?php
//Include database configuration file
include('dbConfig.php');
//Get all occupation data
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
//Count total number of rows
$rowCount = $query->num_rows;
// Create an HTML options string
$htmlOptions = "";
if($rowCount > 0) {
while($row = $query->fetch_assoc()){
$htmlOptions .= '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
$htmlOptions .= '<option value="">occupation not available</option>';
}
// OUTPUT
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?= $htmlOptions; ?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
</body>
</html>
I've always liked this solution myself:
<?php
include('dbConfig.php');
$query = $db->query("SELECT * FROM occupations WHERE status = 1 ORDER BY occupation_name ASC");
$rowCount = $query->num_rows;
ob_start();
if ( $rowCount > 0 ) {
while( $row = $query -> fetch_assoc() ){
echo '<option value="'.$row['occupation_id'].'">'.$row['occupation_name'].'</option>';
}
} else {
echo '<option value="">occupation not available</option>';
}
$values = ob_get_clean();
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>php & html inside a multi line php variable</title>
</head>
<body>
<div class="select-boxes">
<select name="occupation" id="occupation">
<option value="">Select occupation</option>
<?php echo $values; ?>
</select>
<select name="specification" id="specification">
<option value="">Select occupation first</option>
</select>
<select name="expertise" id="expertise">
<option value="">Select specification first</option>
</select>
</div>
</body>
</html>
Im trying to get houses to be filled on the second dropdown from their respective estates selected in the first drop down. Im getting no results in the second dropdown.
This is the HTML:
<div class="col-sm-4 col-xs-12">
<div class="form-group drop-custum">
<select id="estate" name="estate" data-live-search="true" class="form-control show-tick"
onchange="get_houses(this.value)">
<option value="">-- Estate --</option>
<?php
$sql = $this->db->query("select * from estates ORDER BY estate_name asc");
$result = $sql->result();
foreach ($result as $estates):
?>
<option class="text-uppercase"
value="<?= $estates->estate_name?>"> <?= $estates->estate_name?></option>
<?php endforeach; ?>
</select>
</div>
</div>
<div class="col-sm-4 col-xs-12">
<div class="form-group drop-custum">
<select name="house" data-live-search="true" id="house"
class="form-control show-tick">
<option value="">-- House --</option>
</select>
</div>
</div>
This is the AJAX:
function get_houses()
{
$.ajax({
url:"fill_houses/",
type:"POST",
data:'estate_name='+val,
success:function(data)
{
$("#house").html(data);
alert('success');
}
});
}
This is the PHP:
public function fill_houses()
{
$query = "select * from houses where estate_name='" . $_POST["estate_name"] . "' order by house_number asc ";
$result = $query->result();
foreach ($result as $estates):
'<option class="text-uppercase" value="'.$estates->house_id.'"> '.$estates->house_number.'</option>';
endforeach;
}
You must return the value back in php function fill_houses().
public function fill_houses()
{
$query = $this->db->query("select * from houses where estate_name='" . $_POST["estate_name"] . "' order by house_number asc ");
$result = $query->result();
foreach ($result as $estates):
return '<option class="text-uppercase" value="'.$estates->house_id.'"> '.$estates->house_number.'</option>';
endforeach;
}
also in javascript ajax function get_houses() you need to get the variable. and a couple of edit.
function get_houses(val)
{
$.ajax({
url:"fill_houses/",
type:"POST",
data: { 'estate_name': val} ,
success:function(data)
{
$("#house").html(data);
alert('success');
}
});
}
Database Screen Shot
Stream
1)CSE
2)ECE
Semester
1)1
2)3
3)5
Subject
1)DBMS
2)OS
3)DCLD
4)SS
The above three fields are in the database.What i want is when I will select CSE from Stream dropdown box and 3 from Semester dropdown box, DBMS need to be selected from Subject dropdown box and so on.
I have already configured the option selection for two dropdown boxes namely Stream and Subject means when i select option from Stream,corresponding value has selected from Semester Dropdown
The below code runs well.Please help me out by select Subject dropdown from Stream and Semester dropdown
The code is below:
select.php
<html>
<head>
<link rel="stylesheet" type="text/css" href="select_style.css">
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
function fetch_select(val)
{
$.ajax({
type: 'post',
url: 'fetch_data.php',
data: {
get_option:val
},
success: function (response) {
document.getElementById("new_select").innerHTML=response;
}
});
}
</script>
</head>
<body>
<p id="heading">Select Subject for Timesheet</p>
<center>
<div id="select_box">
<select onChange="fetch_select(this.value);">
<option>Select Stream</option>
<?php
$host = 'localhost';
$user = 'xx';
$pass = 'zzz';
mysql_connect($host, $user, $pass);
mysql_select_db('sample');
$select=mysql_query("select stream from streamSub group by stream");
while($row=mysql_fetch_array($select))
{
echo "<option>".$row['stream']."</option>";
}
?>
</select>
<select id="new_select">
</select>
</div>
</center>
</body>
</html>
fetch_data.php
<?php
if(isset($_POST['get_option']))
{
$host = 'localhost';
$user = 'XX';
$pass = 'ZZZ';
mysql_connect($host, $user, $pass);
mysql_select_db('sample');
$stream = $_POST['get_option'];
$find=mysql_query("select subject from streamSub where stream='$stream'");
while($row=mysql_fetch_array($find))
{
echo "<option>".$row['subject']."</option>";
}
exit;
}
?>
Main.php
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Fetch Data Using Ajax</title>
<style type='text/css'>
.hide{
display: none;
}
.show{
display: block;
}
</style>
</head>
<body>
<form>
<div>
<label>
Stream
</label>
<select id="stream">
<option value="">Select Stream</option>
<option value="CSE">CSE</option>
<option value="ECE">ECE</option>
</select>
</div>
<div>
<label>
Semester
</label>
<select id="sem">
<option value="">Select Semester</option>
<option value="1">1</option>
<option value="2">3</option>
<option value="3">5</option>
</select>
</div>
<div id="subjectDiv" class="hide">
<label>
Subject
</label>
<select id='subject'>
</select>
</div>
</form>
</body>
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-3.1.1.min.js"></script>
<script>
$(document).ready(function(){
$('#sem').change(function(){
$.ajax({
url:'getData.php',
type:'POST',
data:{
stream : $('#stream').val(),
sem : $('#sem').val()
},
success:function(result){
console.log(result);
$('#subject').html(result);
$('#subjectDiv').removeClass('hide');
$('#subjectDiv').addClass('show');
}
});
});
});
getData.php
<?php
$con = mysqli_connect('localhost','root','','test');
$query = "SELECT * FROM getdata WHERE stream = '".$_POST['stream']."' AND sem = ".$_POST['sem'];
$row = mysqli_query($con,$query);
echo "<option value=''>Select Subject</option>";
while($data = mysqli_fetch_assoc($row)){
echo "<option value='".$data['subject']."'>".$data['subject']."</option>";
}
?>