I had created a simple on change event in Ajax and trying to get data on the change of select tag [HTML] in another select tag.
All's work fine I got the result on test.php
test.php
<div class="row">
<div class="input-field col s12">
<select name="category" id="category">
<option value="" disabled selected>Choose Category</option>
<?php
include "db-connect/db-connect.php";
$qry = mysqli_query($conn, "SELECT * FROM `category`");
while ($row=mysqli_fetch_assoc($qry)) {
?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['category']; ?></option>
<?php } ?>
</select>
</div>
</div>
<div class="row">
<div class="input-field col s12">
<select name="subcategory" id="subcategory">
<option value="">Choose Sub Category</option>
</select>
</div>
</div>
and the ajax code for this html :-
<script type="text/javascript">
$(document).ready(function(){
$('#category').on('change',function(){
var categoryID = $(this).val();
if(categoryID){
$.ajax({
type:'POST',
url:'ajax/category.php',
data:'category_id='+categoryID,
success:function(html){
$('#subcategory').html(html);
//$('#city').html('<option value="">Select state first</option>');
}
});
}else{
$('#subcategory').html('<option value="">Choose category first</option>');
//$('#city').html('<option value="">Select state first</option>');
}
});
});
</script>
When I run it I got the result but after that, I want to implement it into my project template I got nothing.
But, I get data in the inspect element [F12] -> Network
Ajax data file ajax/category.php:-
<?php
//Include the database configuration file xD
include "../db-connect/db-connect.php";
if(!empty($_POST["category_id"])){
//Fetch all data
$query = mysqli_query($conn,"SELECT * FROM `sub_category` WHERE `category_id` = ".$_POST['category_id']."");
//option list
if(mysqli_num_rows($query) > 0){
echo '<option value="">Select state</option>';
while($row = mysqli_fetch_assoc($query)){
echo '<option value="'.$row['sub_category'].'">'.$row['sub_category'].'</option>';
}
}else{
echo '<option value="">State not available</option>';
}
}
?>
Related
i have a codeigniter website, where there is a form for user to select category and subcategory, when a user selects category the subcategory dropdown should show accordingly, i did the following code:
public function subcategories() {
$category = $this->input->post('category');
$query = $this->db->query('SELECT name FROM subcategory WHERE parentcategory='.$category);
$data['subcategories'] = $query->result_array();
$this->load->view('homecontroller/subcategories', $data);
echo $category;
}
in subcategories.php
<?php foreach ($subcategories as $c): ?>
<option value="<?php echo $c['name'] ?>"><?php echo $c['name'] ?></option>
<?php endforeach; ?>
and in my view:
$(document).ready(function() {
$('#sl_countries').change(function() {
$('#sl_cities').load("<?php echo site_url('index.php/homecontroller/subcategories') ?>", {
category: $(this).val()
});
});
});
<div class="form-group col-md-6">
<label for="inputEmail4">Product Category</label>
<select id="sl_countries" class="form-control" name="cname" aria-label="Default select example">
<?php
foreach($listcategory as $val){
echo '<option value="'.$val->name.'">'.$val->name.'</option>';
}?>
</select>
</div>
<div class="form-group col-md-6">
<label for="inputEmail4">Sub Category</label>
<select class="form-control" name="sname" id="sl_cities"></select>
</div>
however this is not working, i get an error like below when i checked the console:
You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '' at line 1
SELECT name FROM subcategory WHERE parentcategory=
can anyone please tell me what is wrong here, thanks in advance
use this way:-
jQuery Ajax code :-
<script>
$(document).ready(function(){
$('#country').change(function(){
var country_id = $('#country').val();
if(country_id != '')
{
$.ajax({
url:"<?php echo base_url(); ?>dynamic_dependent/fetch_state",
method:"POST",
data:{country_id:country_id},
success:function(data)
{
$('#state').html(data);
$('#city').html('<option value="">Select City</option>');
}
});
}
else
{
$('#state').html('<option value="">Select State</option>');
$('#city').html('<option value="">Select City</option>');
}
});
});
</script>
Controller Code :-
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Dynamic_dependent extends CI_Controller {
function fetch_state()
{
if($this->input->post('country_id'))
{
echo $this->dynamic_dependent_model->fetch_state($this->input->post('country_id'));
}
}
}
?>
Model Code :-
<?php
class Dynamic_dependent_model extends CI_Model
{
function fetch_state($country_id)
{
$this->db->where('country_id', $country_id);
$this->db->order_by('state_name', 'ASC');
$query = $this->db->get('state');
$output = '<option value="">Select State</option>';
foreach($query->result() as $row)
{
$output .= '<option value="'.$row->state_id.'">'.$row->state_name.'</option>';
}
return $output;
}
}
?>
View Code :-
<div class="form-group">
<select name="country" id="country" class="form-control input-lg">
<option value="">Select Country</option>
<?php
foreach($country as $row)
{
echo '<option value="'.$row->country_id.'">'.$row->country_name.'</option>';
}
?>
</select>
</div>
<br />
<div class="form-group">
<select name="state" id="state" class="form-control input-lg">
<option value="">Select State</option>
</select>
</div>
I have two dropdown. I am using Jquery to load second dropdown. without jqyery My php code is working fine. but when I use with jquery second dropdown becomes empty on selection of first drop down.
First Dropdown ( Education )
$sqleducation = "select * from education order by education_id asc ";
$reseducation = mysqli_query($conn,$sqleducation);
<select name="education" id="education">
<option value="-1">Please Select</option>
<?php while($roweducation=mysqli_fetch_array($reseducation)){ ?>
<option value="<?php echo $roweducation['education_id']?>">
<?php echo $roweducation['education_name']?>
</option>
<?php }?>
</select>
Second Drop Down ( Degree)
<select name="degree" id="degree" >
<option value="-1">Please Select</option>
<?php if(isset($_POST["education_id"]) && !empty($_POST["education_id"])){
$sqldegree = "SELECT * FROM degree WHERE education_id = ".$_POST['education_id']." ";
$resdegree = mysqli_query($conn,$sqldegree);
while($rowdegree=mysqli_fetch_array($resdegree))
{ ?>
<option value="<?php echo $rowdegree['degree_id']?>">
<?php echo $rowdegree['degree_name']?>
</option>
<?php } }?>
</select>
Second dropdown is using juery to load on selection of first dropdown Education.
<script src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#education').on('change',function(){
var educationID = $(this).val();
if(educationID){
$.ajax({
type:'POST',
url:'education-career.php',
data:'education_id='+educationID,
success:function(html){
$('#degree').html(html);
}
});
}else{
$('#degree').html('<option value="">Select Education first</option>');
}
});});</script>
Try change below line
data:'education_id='+educationID,
to
data:{education_id : educationID},
Try this.(second select tag have to place in first page in order to use $('#degree').html(...))
First Dropdown
$sqleducation = "select * from education order by education_id asc ";
$reseducation = mysqli_query($conn,$sqleducation);
<select name="education" id="education">
<option value="-1">Please Select</option>
<?php while($roweducation=mysqli_fetch_array($reseducation)){ ?>
<option value="<?php echo $roweducation['education_id']?>">
<?php echo $roweducation['education_name']?>
</option>
<?php }?>
</select>
<select name="degree" id="degree" >
<option value="-1">Please Select</option>
</select>
Second Dropdown
<option value="-1">Please Select</option>
<?php if(isset($_POST["education_id"]) && !empty($_POST["education_id"])){
$sqldegree = "SELECT * FROM degree WHERE education_id = ".$_POST['education_id']." ";
$resdegree = mysqli_query($conn,$sqldegree);
while($rowdegree=mysqli_fetch_array($resdegree))
{ ?>
<option value="<?php echo $rowdegree['degree_id']?>">
<?php echo $rowdegree['degree_name']?>
</option>
<?php } }?>
Here in ajax, you are using the
data:'education_id='+educationID,
Which is used to post the data. and the variable name will be here education_id.
And in your second page you are trying to get:
isset($_POST["education"])
this only. So on second page you have to replace education with education_id.
change:
$('#education').on('change',function(){
To:
$('select#education').change(function(){
I am working on a registration page where a user when selects its designation, its corresponding reporting head gets selected in "reporting head" field dynamically. I have used Ajax for this but somehow the reporting head field remains empty. Can I get some insights over this?? It will be highly appreciated.
Here goes my registration fields,
<select name="designation" class="form-control" required="" id="desig" >
<option selected="selected" >Select your option</option>
<?php
$sql = mysql_query("SELECT id, designation FROM tbl_designation where id in (1,2,3,4)");
while ($row = mysql_fetch_assoc($sql)){
echo "<option value=" . $row['id'] . ">" . $row['designation'] . "</option>";
}
?></select>
<select name="reporting_head" class="form-control" required="" id="rephead">
<option selected="selected">Select your option</option>
</select>
Now JavaScript+AJAX that I am applying,
$(document).ready(function()
{
$("#desig").change(function()
{
var id=$(this).val();
var dataString = 'id='+ id;
$.ajax
({
type: "POST",
url: "ajax_rep.php",
data: dataString,
cache: false,
success: function(html)
{
$("#rephead").html(html);
}
});
});
});
And finally my ajax_rep.php
<?php
require("includes/config.php");
require("classes/Database.class.php");
if($_POST['id'])
{
$id=$_POST['id'];
$sql=mysql_query("SELECT reporting_head_id, reporting_head FROM `tbl_designation` WHERE id='$id'");
while($row=mysql_fetch_array($sql))
{
$id=$row['reporting_head_id'];
$data=$row['reporting_head'];
echo '<option value="'.$id.'">'.$data.'</option>';
}
}
?>
This is the HTML I am getting on ajax success,
<div class="row row-offcanvas row-offcanvas-right">
<!--/.col-xs-12.col-sm-9-->
<div class="col-sm-3 col-md-3 sidebar" id="sidebar">
<div id="left_panel" class="clearfix left">
<option value="6">Sales Head</option>
try this in you loop while
$list = '<option selected="selected">Select your option</option>';
while($row=mysql_fetch_array($sql))
{
$id=$row['reporting_head_id'];
$data=$row['reporting_head'];
$list .= '<option value="'.$id.'">'.$data.'</option>';
}
}
echo $list;
And in your ajax success function do this
success: function(html)
{
$("#rephead").html("");
$("#rephead").append(html);
}
I have database with 5 tables. Each table is a subcatagory of the previous one, called:
countries
states
cities
ZIPcode
streets
Now I have 3 dropdowns which depend on each other. So when I select countries: USA, the next dropdown wil only show USA-states etc. This works.
But now I want to extend to 5 dropdowns, so adding 2 more.
I don't show what I've tried to add 2 more, because it will probably only make it more complex.
So I show the 3 dropdowns that are working now:
file: ajax.php
<?php
//dbConfig is not added here, but it connects to database
include('dbConfig.php');
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
//Get 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;
//Display states 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>';
}
}
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
//Get 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;
//Display cities 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>';
}
}
?>
****The index.php-file**** (I didn't add the css):
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="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>
</head>
<body>
<div class="select-boxes">
<?php
//Include database configuration file
include('dbConfig.php');
//Get all 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 name="country" 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 name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
</div>
</body>
</html>
You need to create a two more table zipcode and streets and add a city_id in zipcode table and zip_id in streets table
<select name="zipcode" id="zipcode">
<option value="">Select Zipcode first</option>
</select>
<select name="streets" id="streets">
<option value="">Select Streets first</option>
</select>
Jquery Scrtipt
$('#city').on('change',function(){
var cityId = $(this).val();
if(cityId){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'city_id='+cityId,
success:function(html){
$('#zipcode').html(html);
}
});
}else{
$('#zipcode').html('<option value="">Select zipcode first</option>');
}
});
});
$('#zipcode').on('change',function(){
var zipId = $(this).val();
if(zipId){
$.ajax({
type:'POST',
url:'ajaxData.php',
data:'zip_id='+zipId,
success:function(html){
$('#streets').html(html);
}
});
}else{
$('#streets').html('<option value="">Select Streets first</option>');
}
});
});
Php code is same as state just need to change table name and fields
By using this you get the cascading dropdown menu of zipcode and streets.
See, I modified your code a little bit.
I don't have any idea about your street & zipcode table column name or dropdown. I assumed and did.
Change it wherever needed in dropdow or in query.
It will help you.
Go through it.
And, if any doubt, feel free to ask.
index.php
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
</head>
<body>
<div class="select-boxes">
<?php include('dbConfig.php'); //Include database configuration file ?>
<div class="country">
<?php
$query = $db->query("SELECT * FROM countries WHERE status = 1 ORDER BY country_name ASC");
$rowCount = $query->num_rows;
?>
<select name="country" 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>
</div>
<div class="showStateCity">
<select name="state" id="state">
<option value="">Select country first</option>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
</select>
<select name="zipcode" id="zipcode">
<option value="">Select City first</option>
</select>
<select name="streets" id="streets">
<option value="">Select Zipcode first</option>
</select>
</div>
</div>
</body>
</html>
<script src="jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#country').on('change',function(){
getStateCityZipCodeStreets();
});
$('#state').on('change',function(){
getStateCityZipCodeStreets();
});
$('#city').on('change',function(){
getStateCityZipCodeStreets();
});
$('#zipcode').on('change',function(){
getStateCityZipCodeStreets();
});
function getStateCityZipCodeStreets(){
var country = $('#country').val();
var state = $('#state').val();
var city = $('#city').val();
var zipcode = $('#zipcode').val();
$.ajax({
type:'POST',
url:'ajaxData.php',
data:{country_id:country, state_id :state, city_id : city, zipcode_id : zipcode},
cache:false,
success:function(data){
$('.showStateCity').html(data);
}
});
}
});
</script>
ajaxData.php
<?php
//dbConfig is not added here, but it connects to database
include('dbConfig.php');
/*States*/
$queryState = "SELECT * FROM states WHERE 1=2";
if(isset($_POST["country_id"]) && !empty($_POST["country_id"])){
$queryState = "SELECT * FROM states WHERE status = 1 AND country_id =".$_POST['country_id']." ORDER BY state_name ASC";
}
$execQueryState = $db->query($queryState);
$rowCountState = $execQueryState->num_rows;
/*City*/
$queryCity = "SELECT * FROM cities WHERE 1=2";
if(isset($_POST["state_id"]) && !empty($_POST["state_id"])){
$queryCity = "SELECT * FROM cities WHERE status = 1 AND state_id".$_POST['state_id']." ORDER BY city_name ASC";
}
$execQueryCity = $db->query($queryCity);
$rowCountCity = $execQueryCity->num_rows;
/*ZipCode*/
$queryZipcode = "SELECT * FROM zipcode WHERE 1=2";
if(isset($_POST["city_id"]) && !empty($_POST["city_id"])){
$queryZipcode = "SELECT * FROM zipcode WHERE status = 1 AND city_id".$_POST['city_id']." ORDER BY zipcode ASC";
}
$execQueryZipCode = $db->query($queryZipcode);
$rowCountZipCode = $execQueryZipCode->num_rows;
/*Streets*/
$queryStreets = "SELECT * FROM streets WHERE 1=2";
if(isset($_POST["zipcode_id"]) && !empty($_POST["zipcode_id"])){
$queryStreets = "SELECT * FROM streets WHERE status = 1 AND zipcode_id".$_POST['zipcode_id']." ORDER BY street_name ASC";
}
$execQueryStreets = $db->query($queryStreets);
$rowCountStreets = $execQueryStreets->num_rows;
?>
<select name="state" id="state">
<option value="">Select country first</option>
<?php
if($rowCountState > 0){
while($rowState = $execQueryState->fetch_assoc()){
?>
<option value="<?php echo $rowState['state_id'];?>"><?php echo $rowState['state_name'];?></option>
<?php }
} else {?>
<option value="">State Not Available</option>
<?php }?>
</select>
<select name="city" id="city">
<option value="">Select state first</option>
<?php
if($rowCountCity > 0){
while($rowCity = $execQueryCity->fetch_assoc()){
?>
<option value="<?php echo $rowCity['city_id'];?>"><?php echo $rowCity['city_name'];?></option>
<?php }
} else {?>
<option value="">City Not Available</option>
<?php }?>
</select>
<select name="zipcode" id="zipcode">
<option value="">Select City first</option>
<?php
if($rowCountZipCode > 0){
while($rowZipCode = $execQueryZipCode->fetch_assoc()){
?>
<option value="<?php echo $rowZipCode['zipcode_id'];?>"><?php echo $rowZipCode['zipcode'];?></option>
<?php }
} else {?>
<option value="">ZipCode Not Available</option>
<?php }?>
</select>
<select name="streets" id="streets">
<option value="">Select ZipCode first</option>
<?php
if($rowCountStreets > 0){
while($rowStreets = $execQueryStreets->fetch_assoc()){
?>
<option value="<?php echo $rowStreets['street_id'];?>"><?php echo $rowStreets['street_name'];?></option>
<?php }
} else {?>
<option value="">Streets Not Available</option>
<?php }?>
</select>
I'm trying to post the values that I get from each dropdown menu, this is an n-level, however I'm going to use them maximum of 3. How can I post every value i get from each selection?
<?php
include('dbcon.php');
if($_REQUEST)
{
$id = $_REQUEST['parent_id'];
$query = "select * from ajax_categories where pid = ".$id;
$results = #mysql_query( $query);
$num_rows = #mysql_num_rows($results);
if($num_rows > 0)
{?>
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
<?php
while ($rows = mysql_fetch_assoc(#$results))
{?>
<option value="<?php echo $rows['id'];?>"><?php echo $rows['category'];?></option>
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found !</label>';}
}
?>
http://www.99points.info/2010/12/n-level-dynamic-loading-of-dropdowns-using-ajax-and-php/
change the select option of your like this
<select name="sub_category" class="parent">
<option value="" selected="selected">-- Sub Category --</option>
while ($rows = mysql_fetch_assoc(#$results))
{?>
echo '<option value="'.$row['id'].'">'.$rows['category'].'</option>';
<?php
}?>
</select>
<?php
}
else{echo '<label style="padding:7px;float:left; font-size:12px;">No Record Found !</label>';}
}
</select>