PHP Ajax dependent dropdown not working - php

I am trying to implement dependent dropdown using ajax and php. But anyhow the response from second dropdown is not coming. after checking in console, I am able to see the id of first dropdown but no response from second dropdown. So, When i click on first dropdown, I just get a blank value in Second dropdown.
HTML Code
<div class="col-md-6">
<?php
require_once('db.php');
$varient_result = $conn->query('select * from tv_varient');
?>
<select name="varient" id="varient-list" class="form-control c-square c-theme" required>
<option value="">Select Varient</option>
<?php
if ($varient_result->num_rows > 0) {
// output data of each row
while($row = $varient_result->fetch_assoc()) {
?>
<option value="<?php echo $row["id"]; ?>"><?php echo $row["name"]; ?></option>
<?php
}
}
?>
</select>
</div>
</br></br>
<label for="inputPassword3" class="col-md-4 control-label" style="margin-left: 15px;">Price:</label>
<div class="col-md-6">
<select name="price" id="price-list" class="form-control c-square c-theme" required>
<option value=''>Select Price *</option>
</select>
<div>
</div>
</div>
</div>
</div>
</div>
AJAX Code
<script>
$('#varient-list').on('change', function(){
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
</script>
get_price.php
?php
require_once('db.php');
//$country_id = mysqli_real_escape_string($_POST['country_id']);
//var_dump($country_id);
//var_dump($_POST['country_id']);
$varient_id = $_POST['veriant_id'];
echo $varient_id;
//var_dump($varient_id);
var_dump($_POST['varient_id']);
if($varient_id!='')
{
$states_result = $conn->query('select * from tv_price where veriant_id='.$varient_id.'');
$options = "<option value=''>Select Price</option>";
while($row = $states_result->fetch_assoc()) {
$options .= "<option value='".$row['price']."'>".$row['price']."</option>";
}
echo $options;
}
?>

Try below code,
$(document).on('change', '#varient-list', function(e)
{
var varient_id = this.value;
$.ajax({
type: "POST",
url: "get_price.php",
data:'varient_id='+varient_id,
success: function(result){
$("#price-list").html(result);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

varient_id & veriant_id on the POST is wrong (the e & a difference).
$varient_id = $_POST['veriant_id']; should be $varient_id = $_POST['varient_id'];

Related

Getting value of the selected items php mysql html [duplicate]

I'm trying to populate a Select Box based in the choice of the first Select Box, but I'm having some troubles doing it. Simply nothing happens.
What I have until now (this is on my footer):
<script src="./plugins/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.category").change(function(){
var selectedCategory = $(".category option:selected").val();
$.ajax({
type: "POST",
url: "../inc/get_subcat.php",
data: { category : selectedCategory }
}).done(function(data){
$("#subcategory").html(data);
});
});
});
</script>
The page with the div is located at /pages/file.php:
<div class="col-md-6">
<div class="form-group">
<label class="control-label">SubCategory</label>
<div id="subcategory"> </div>
</div> </div>
The file that does the query is in another folder (inc/get_subcat.php):
<?php
include("config.php");
if(isset($_POST['category'])){
$cat = validar($_POST['category']);
$query = "SELECT id, subcategory FROM subcategories WHERE catid = ?";
#Prepare stmt or reports errors
($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
#Execute stmt or reports errors
$stmt->bind_param("i", $cat);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
#Save data or reports errors
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
#Check if are rows in query
if ($stmt_result->num_rows>0) {
echo "<select class='form-control' id='subcategory' name='subcategory'>";
# Save in $row_data[] all columns of query
while($row_data = $stmt_result->fetch_assoc()) {
# Action to do
echo "<option value='$row_data[id]'>$row_data[category]</option>";
}
echo "</select>";
}
$stmt->close();
}
?>
There is someone that could help me trying to fix this error? Can't fix despite trying for some hours.
Thanks!
Edit:
This is the HTML code with all Select Box:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Category</label>
<select class='form-control' id='category' name='category'><option value='1'>Categoria 1</option><option value='2'>Categoria 2</option></select> </div>
</div>
<div class="col-md-6" id="subcategory">
</div>
</div>
In your HTML you have<select class='form-control'...etc
So the <select> has a class "form-control" only.
But your selector is $("select.category").change...etc. which means it's looking for a select with "category" in the class attribute (the dot . in the selector signifies a class). Such an element doesn't exist, hence why nothing happens.
Perhaps you meant to use the ID (in which case $("#category").change...etc)? Either that or you need to write <select class='form-control category'...etc before it will work.
May be problem in your array data or query. So please check it first.
I post here working example of depending drop down may be this will help you.
PHP code
$sub_category // Your array of Subcategory;
if ($sub_category) {
echo '<option value="">Sub Category</option>';
foreach ($sub_category as $sub_category) {
$selected = '';
if($sub_category['sub_category_id'] == $data['product']['sub_category_id'])
{
$selected = 'selected';
}
echo '<option value="' . $sub_category['sub_category_id'] . '" '.$selected.'>' . $sub_category['sub_category'] . '</option>';
}
}
JS code
<script type="text/javascript">
loadSubCategory();
jQuery(document).ready(function($) {
$(document).on('change', '.category_id', function(event) {
event.preventDefault();
loadSubCategory();
});
});
function loadSubCategory()
{
var category_id = $(".category_id option:selected").val();
$.ajax({
url: 'Your Path Of server Function',
type: 'post',
data: {category_id: category_id, product_id : "<?= $product['product_id']?>" },
cache: false,
success: function (resp) {
if(resp)
{
$('.sub_category_id').html(resp);
} else {
$('.sub_category_id').html('<option value="">Sub Category</option>');
}
}
})
}
</script>
HTML Code
<div class="form-group">
<b>Product Category </b>
<select class="form-control category_id" id="category_id" name="category_id">
<option>Category</option>
<?php
<option value="<?= $value['category_id'] ?>" <?=$selected ?> ><?= $value['category'] ?></option>
</select>
</div>
<!-- Category End -->
<!-- Sub Category Start -->
<div class="form-group">
<b>Product Sub Category </b>
<select class="form-control sub_category_id" name="sub_category_id">
<option value="">Sub Category</option>
<option value="">Sub Category</option>
<option value="20">Books Stationery</option>
<option value="21">Gaming and Accessories</option>
<option value="22">Music Musical Instruments</option>
</select>
</div>

Show sub-options based on selected main option in Codeigniter by ajax

I would like when I select the cats option that only the breed of cats appears, such as the Siamese example. If I select dog, I only want to get the breed of dogs, such as Pitbull and others.
Can you help me with the code, it tells me to use jquery, but how is it done I am just learning?
<div class="form-group">
<div class="row">
<div class="col-12 col-sm-6">
<label for="especie">Especie</label>
<select class="form-control" id="id_especie" name="id_especie" value="data-id-especie=">
<option value="">Seleccionar especie</option>
<?php foreach ($especie as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<option value="">Seleccionar raza</option>
<?php foreach ($raza as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
</div>
</div>
According to your Question you want Dynamic dependant drop down list in codeigniter with ajax / jQuery.
PHP VIEW :
<div class="col-12 col-sm-6">
<label for="especie">Especie</label>
<select class="form-control" id="id_especie" name="id_especie" value="data-id-especie=">
<option value="">Seleccionar especie</option>
<?php foreach ($especie as $row) {?>
<option value="<?php echo $row['id']; ?>"><?php echo $row['nombre']; ?></option>
<?php }?>
</select>
</div>
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<!-- Data here will be auto populated by ajax -->
</select>
</div>
Controller :
public function get_data()
{
$id_especie = $this->input->post("id_especie");
$SUbCatdata = $this->db->get_where('tableName',array('id'=>$id_especie))->result_array();
$option ="<option selected disabled value=''>Select Name</option>";
foreach($SUbCatdata as $row)
{
$option.="<option value='".$row['id']."'>".$row['nombre']."</option>";
}
echo $option;
}
jQuery / Ajax :
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#id_especie").on("change",function(){
var id_especie = $(this).val();
$.ajax({
url : "<?php echo base_url('Controller/get_data') ?>",
type: "post",
data: {"id_especie":id_especie},
success : function(data){
//alert(data);
$("#id_raza").html(data);
}
});
});
</script>
Note : For more info regarding change()
https://api.jquery.com/change
If I understand you correctly, you want to create a sub-dropdown list that is dependent on the selection of another (main) dropdown list. If this is the case, here's what you need to do.
First, you need to create a file that contains code that will fetch results based on what is supplied. That is (in your example), if the main category is "dogs", it will query the database for all "species" of dogs, and return the result. Something like this:
Category Controller
class Category_controller extends CI_Controller{
// Get Subcategory method
public function get_subcategory()
{
// Check if input ($_GET or $_POST) exists
if ( $this->input->post_get() )
{
$main_cat_id = $this->input->post_get('mainid'); // main category id
// Perform your db query here to get the subcategory of the main cat
// Echo the result after performing a foreach loop like you did in the
// html file. <option value="value_id">value name</option>
$result = ""; // store empty value first
foreach ($dbresult as $value)
{
$result .= '<option value="$value['id']">$value['nombre']</option>';
}
echo $result;
}
}
}
SubCategory.js
$(document).ready(function() {
$('select[name="id_especie"]').on('change', function() {
var catid = $(this).val(); // will get the value attribute of the selected main category
// Perform ajax request
$.ajax({
url: 'url-to-the-subcategory-controller', // remember to set this in your config/routes.php file
method: 'POST',
cache: false,
data: {mainid: catid},
dataType: 'html',
success: function(data) {
$('select#id_raza').html(data); // update the subcategory dropdown
},
error: function(data) {
console.log(data);
}
});
})
});
So, your second select box select#id_raza show look like so in your view file:
<div class="col-12 col-sm-6">
<label for="raza">Raza</label>
<select class="form-control" id="id_raza" name="id_raza">
<option value="">Seleccionar raza</option>
<!-- Data here will be auto populated by ajax -->
</select>
</div>

Populate Select based on another Select

I'm trying to populate a Select Box based in the choice of the first Select Box, but I'm having some troubles doing it. Simply nothing happens.
What I have until now (this is on my footer):
<script src="./plugins/bower_components/jquery/dist/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.category").change(function(){
var selectedCategory = $(".category option:selected").val();
$.ajax({
type: "POST",
url: "../inc/get_subcat.php",
data: { category : selectedCategory }
}).done(function(data){
$("#subcategory").html(data);
});
});
});
</script>
The page with the div is located at /pages/file.php:
<div class="col-md-6">
<div class="form-group">
<label class="control-label">SubCategory</label>
<div id="subcategory"> </div>
</div> </div>
The file that does the query is in another folder (inc/get_subcat.php):
<?php
include("config.php");
if(isset($_POST['category'])){
$cat = validar($_POST['category']);
$query = "SELECT id, subcategory FROM subcategories WHERE catid = ?";
#Prepare stmt or reports errors
($stmt = $mysqli->prepare($query)) or trigger_error($mysqli->error, E_USER_ERROR);
#Execute stmt or reports errors
$stmt->bind_param("i", $cat);
$stmt->execute() or trigger_error($stmt->error, E_USER_ERROR);
#Save data or reports errors
($stmt_result = $stmt->get_result()) or trigger_error($stmt->error, E_USER_ERROR);
#Check if are rows in query
if ($stmt_result->num_rows>0) {
echo "<select class='form-control' id='subcategory' name='subcategory'>";
# Save in $row_data[] all columns of query
while($row_data = $stmt_result->fetch_assoc()) {
# Action to do
echo "<option value='$row_data[id]'>$row_data[category]</option>";
}
echo "</select>";
}
$stmt->close();
}
?>
There is someone that could help me trying to fix this error? Can't fix despite trying for some hours.
Thanks!
Edit:
This is the HTML code with all Select Box:
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">Category</label>
<select class='form-control' id='category' name='category'><option value='1'>Categoria 1</option><option value='2'>Categoria 2</option></select> </div>
</div>
<div class="col-md-6" id="subcategory">
</div>
</div>
In your HTML you have<select class='form-control'...etc
So the <select> has a class "form-control" only.
But your selector is $("select.category").change...etc. which means it's looking for a select with "category" in the class attribute (the dot . in the selector signifies a class). Such an element doesn't exist, hence why nothing happens.
Perhaps you meant to use the ID (in which case $("#category").change...etc)? Either that or you need to write <select class='form-control category'...etc before it will work.
May be problem in your array data or query. So please check it first.
I post here working example of depending drop down may be this will help you.
PHP code
$sub_category // Your array of Subcategory;
if ($sub_category) {
echo '<option value="">Sub Category</option>';
foreach ($sub_category as $sub_category) {
$selected = '';
if($sub_category['sub_category_id'] == $data['product']['sub_category_id'])
{
$selected = 'selected';
}
echo '<option value="' . $sub_category['sub_category_id'] . '" '.$selected.'>' . $sub_category['sub_category'] . '</option>';
}
}
JS code
<script type="text/javascript">
loadSubCategory();
jQuery(document).ready(function($) {
$(document).on('change', '.category_id', function(event) {
event.preventDefault();
loadSubCategory();
});
});
function loadSubCategory()
{
var category_id = $(".category_id option:selected").val();
$.ajax({
url: 'Your Path Of server Function',
type: 'post',
data: {category_id: category_id, product_id : "<?= $product['product_id']?>" },
cache: false,
success: function (resp) {
if(resp)
{
$('.sub_category_id').html(resp);
} else {
$('.sub_category_id').html('<option value="">Sub Category</option>');
}
}
})
}
</script>
HTML Code
<div class="form-group">
<b>Product Category </b>
<select class="form-control category_id" id="category_id" name="category_id">
<option>Category</option>
<?php
<option value="<?= $value['category_id'] ?>" <?=$selected ?> ><?= $value['category'] ?></option>
</select>
</div>
<!-- Category End -->
<!-- Sub Category Start -->
<div class="form-group">
<b>Product Sub Category </b>
<select class="form-control sub_category_id" name="sub_category_id">
<option value="">Sub Category</option>
<option value="">Sub Category</option>
<option value="20">Books Stationery</option>
<option value="21">Gaming and Accessories</option>
<option value="22">Music Musical Instruments</option>
</select>
</div>

CSRF Protection True and ajax code not working

I have CSRF Protection True in config.php.
After I click standard/class Name then the ajax request is not working.
Please help me, Thank you.
View code:
<?php echo form_open('admin/Teacher/add_teacher_by_subject') ?>
<div class="form-group">
<label>Standard / Class Name<span class="text-danger">*</span></label>
<select class="form-control" name="standard_name" id="standard_name" style="width: 100%;">
<option value="">----Select Standard / Class----</option>
<?php foreach ($standard as $value): ?>
<option value="<?php echo $value['standard_id'] ?>"><?php echo $value['standard_name']; ?></option>
<?php endforeach; ?>
</select>
</div>
<div class="form-group">
<label>Section<span class="text-danger">*</span></label>
<select class="form-control" name="section_name" id="section_name" style="width: 100%;">
</select>
</div>
<?php form_close() ?>
AJAX code:
<script>
$(document).ready(function () {
$('#standard_name').change(function () {
var standard_id = $('#standard_name').val();
if (standard_id != "") {
var post_url = base_url + "admin/Teacher/get_section_name/" + standard_id;
// console.log(standard_id);
$.ajax({
type: "POST",
url: post_url,
success: function (result)
{
var obj = JSON.parse(result);
var options = "";
options = "<option value=''>----Select Section / Division----</option>";
for (x in obj) {
options += "<option value='" + obj[x].section_id + "'>" + obj[x].section_name + "</option>";
}
document.getElementById("section_name").innerHTML = options;
} //end success
}); //end AJAX
}
});
});
</script>

Select row table using ajax and php

I have a drop menu that includes some category every category has their own subcategory i want to show them buy selecting category name
but it's not working, did i miss something or am i doing it completely wrong?
<script type="text/javascript">
$(function() {
$("#error").hide();
$("#category").change(function(){
$("#error").hide();
var category = $("#category").val();
if (category == "") {
$("#error").show();
return false;
}
var data = $("#form").serialize();
$.ajax({
type:"POST",
url:"index.php",
data:data,
success: function(){
}
});
return false;
});
});
</script>
<form id="form" name="form">
<label for="category" id="error">Empty</label>
<select name="category" id="category">
<option></option>
<option value="News">News</option>
<option value="Items">Items</option>
<option value="Updates">Updates</option>
</select>
</form>
<?php
include("connect.php");
if(!empty($_POST['category'])){
$sql=$con->prepare("SELECT * FROM categorys WHERE category=:category ");
$sql->bindparam(":category",$_POST['category']);
$sql->execute();
while($r=$sql->fetch()){
echo $r['subcategory'];
}
}
?>
SomePage.php
<form id="form" name="form">
<div id='category'>
<label for="category" id="error">Empty</label>
<select name="category" id="category">
<option></option>
<option value="News">News</option>
<option value="Items">Items</option>
<option value="Updates">Updates</option>
</select>
</div>
<div id='subcategory'>
</div>
</form>
<script>
$('#category').change(function(){
var CatName= $('#category').val();
$.ajax({url:"AjaxSelectCategory.php?CatName="+CatName,cache:false,success:function(result){
$('#subcategory').html(result);
}});
});
</script>
Create New Page AjaxSelectCategory.php
[NOTE: If you want to change this page name. Change in <script></script> tag too. Both are related.]
<?php
include("connect.php");
if(!empty($_GET['CatName']))
{
$sql=$con->prepare("SELECT * FROM categorys WHERE category=:category ");
$sql->bindparam(":category",$_GET['CatName']);
$sql->execute();
?>
<select name='subcategory'>
<?php
while($r=$sql->fetch())
{?>
<option value="<?php echo $r['subcategory'];?>"><?php echo $r['subcategory'];?></option>
</select>
<?php }
}?>
Try like this,
$.ajax({
type:"POST",
url:"get_subcategory.php",
data:data,
success: function(data){
alert(data)// this will have the second dropdown. add to desired place in your view.
}
});
In get_subcategory.php
$sql = "Select * from table_name where catregory = ".$_POST'category'];
// execute the query.
$sub = "<select name='sub-category'>";
foreach(result from database as $row) {
$sub .= "<option value='$row->id'>$row->name</option>";
}
$sub .= "</select>";
echo $sub;

Categories