cascading dropdown not Working in Laravel 7 - laravel

i am trying to use cascading dropdown list in mvc. main category is working but in subcategory having some problem.it doesn't show any value when i choose from main category
in Blade:
<div class="form-group">
<label for="cat_id">Category <span class="text-danger">*</span></label>
<select name="cat_id" id="cat_id" class="form-control">
<option value="">--Select any category--</option>
#foreach($categories as $key=>$cat_data)
<option value='{{$cat_data->id}}'>{{$cat_data->title}}</option>
#endforeach
</select>
</div>
<div class="form-group" id="child_cat_div">
<label for="child_cat_id">Sub Category</label>
<select name="child_cat_id" id="child_cat_id" class="form-control">
<option value="">--Select any category--</option>
</select>
</div>
#push('scripts')
<script>
$('#cat_id').on('change',function(e) {
var cat_id=$(this).val();
// alert(cat_id);
if(cat_id !=null){
// Ajax call
$.Ajax({
url:"/backend/category/"+cat_id,
data:{
_token:"{{csrf_token()}}",
id:cat_id
},
type:"POST",
success:function(response){
if(typeof(response) !='object'){
response=$.parseJSON(response)
}
// console.log(response);
var html_option="<option value=''>Select sub category</option>"
if(response.status){
var data=response.data;
// alert(data);
if(response.data){
$('#loader').css("visibility", "visible");
// $('#child_cat_div').removeClass('d-none');
$.each(data,function(id,title){
html_option +="<option value='"+ id +"'>" + title +"</option>"
});
}
else{
}
}
else{
$('#child_cat_div').addClass('d-none');
}
$('#child_cat_id').html(html_option);
}
});
}
else{
}
}) </script> #endpush
in Route:
Route::POST('/category/{id}','Admin\CategoryController#getChildByParent');
in article Controller:
public function create()
{
$categories=Category::where('is_parent',1)->get();
$photos = Photo::all();
$tags = Tag::all();
$articles = Article::all();
return view('backend.articles.create',
compact('categories','photos','tags','articles'));
}
in Category Controller:
public function getChildByParent(Request $request){
$category=Category::findOrFail($request->id);
$child_cat=Category::getChildByParentID($request->id);
return response()->json([$child_cat]);
return response()->json([
'child_cat' => $child_cat]);
}
in model category:
public static function getChildByParentID($id){
return Category::where('parent_id',$id)->orderBy('id','ASC')->pluck('title','id');
}

Related

Laravel How to append Ajax json in Select option

what is issue with my code, it returns empty drop down. i want drop down of nationality table, in teachers profile.
View:
<select class="form-control" name="nation_id" id="nation_id">
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id"
value="{{ #$teacher->nation_id}}">
</select>
ajax code which returns empty dropdown: Ajax:
<script>
$(document).ready(function($){
$.get('nations-list', function(data) {
let teacher_nation_id = $('#teacher_nation_id').val();
let nations = $('#nation_id');
nations.empty();
$.each(data, function(key, value) {
nations.append("<option value='"+ key +"'>" + value + "</option>");
});
nations.val(teacher_nation_id);
});
});
</script>
My Controller:
public function ajaxrequest(Request $request)
{
$nations = Nation::all()->pluck('nation', 'id');
return response()->json($nations);
}
Here is my route:
Route:
Route::get('nations-list','TeachersController#ajaxrequest');
Try this,
<input type="hidden" name="teacher_nation_id" id="teacher_nation_id"
value="{{ #$teacher->nation_id}}">
<select class="form-control" name="nation_id" id="nation_id">
</select>
<select class="form-control" name="area" id="area">
</select>
Ajax code:
<script type="text/javascript">
$(document).ready(function($){
$('#nation_id').click(function($){
var tid = $('#teacher_nation_id').val();
if(tid){
$.ajax({
type:"get",
url:"{{url('/getNation)}}/"+tid,
success:function(res)
{
$('#nation_id').empty();
$("#nation_id").append('<option>--Select Nation--</option>');
if(res)
{
$.each(res,function(key,value){
$('#nation_id').append($("<option/>", {
value: key,
text: value
}));
});
}
}
});
}
});
$('#nation_id).change(function(){
var nid = $(this).val();
if(nid){
$.ajax({
type:"get",
url:"{{url('/getArea')}}/"+nid,
success:function(res)
{
$("#area").empty();
$("#area").append('<option>--Select Area--</option>');
if(res)
{
$.each(res,function(key,value){
$('#area').append($("<option/>", {
value: key,
text: value
}));
});
}
}
});
}
});
});
</script>
Controller:
public function getNation($id)
{
$nations= DB::table("nations")
->where("teacher_nation_id",$id)
->pluck("nation","id")
->toArray();
return response()->json($nations);
}
public function getArea($id)
{
$areas= DB::table("areas")
->where("nation_id",$id)
->pluck("area","id")
->toArray();
return response()->json($areas);
}
Route:
Route::get('/getNation/{id}','NationsController#getNation);
Route::get('/getArea/{id}','AriasController#getArea);
//Here I assumes that You have different controller named AreasController you can gave name of your controller
Hope it will useful for you..
Good Luck...

Laravel 5 multi dynamic dropdown

I'm trying to use the data of the first dropdown, to fill the second.
An example here:
https://gitlab.com/Bons/laravel5.3_dynamic_dropdown/blob/master/readme.md
Controller functon return data, but second dropdown is empty.
First dropdown:
<span>Country: </span>
<select style="width: 200px" class="country" id="id_country">
<option value="0" disabled="true" selected="true">-Select-</option>
#foreach($countries as $contry)
<option value="{{$contry->id_country}}">{{$contry->name}}</option>
#endforeach
</select>
linked dropdown:
<label>City
<select id="region" class="form-control input-sm" name="region_id">
<option value=""></option>
</select>
</label>
Script:
<script type="text/javascript">
$(document).ready(function(){
$(document).on('change','.country',function(){
console.log("hmm its change");
var id=$(this).val();
console.log(id)
$.ajax({
type:'get',
url:'{!!URL::to('findRegions')!!}',
data:{'id':id},
success:function(data) {
console.log("success");
console.log(data.length);
console.log(data);
$.each(data, function(index,subCatObj){
// console.log(subCatObj.name)
$('#region').append(''+subCatObj.name+'');
});
},
error:function(){
console.log("error");
}
});
});
});
</script>
Route:
Route::get('/findRegions/','GirlsController#findRegions');
Controller function:
public function findRegions(Request $request){
$id=$request->id;
$regions=Region::select('name')
->where('id_country',$id)
->get();
dump($regions);
return $regions;
}
Here is how i did it,
in routes/web.php
Route::post('select-ajax', 'Main#selectAjax')->name('select-ajax');
in Controller : Main.php
public function __construct()
{
View::share('selectAllCountries', Country::pluck("name","id")->all());
}
public function selectAjax(Request $request)
{
if($request->ajax())
{
$getRegion = Region::where('id_country',$request->id)->pluck("nameOfTheRegion","id")->all();
$data = view('ajax-select',compact('getRegion'))->render();
return response()->json(['options'=>$data]);
}
}
then create a simple blade file name ajax-select.blade.php
<option selected disabled>--- Select Region---</option>
#if(!empty($getRegion))
#foreach($getRegion as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
#endif
Ajax call
{!! Form::select('country',[' '=>'--- Select Country ---']+$selectAllCountries,null,['class'=>'form-control']) !!}
{!! Form::select('region',[' '=>'--- Select Region---'],null,['class'=>'form-control']) !!}
<script>
$("select[name='country']").change(function(){
var id = $(this).val();
var token = $("input[name='_token']").val();
$.ajax({
url: "{{ route('select-ajax') }}",
method: 'POST',
data: {'id':id, '_token':token},
success: function(data) {
$("select[name='region']").html('');
$("select[name='region']").html(data.options);
},
error:function(){
alert("error!!!!");
}
});
});
</script>
Hope this helps

Creating a cascade drop down without primary and foriegn key relationship with coeigniter

This is the structure of my table "task"
projectname
employee
clientname
task
Dependencies are as follows
One project has multiple task
One project has multiple employees
I need to create a dropdown list when user selects a particular project tasks relevant to them will automatically load to the next dropdown list. In this situation I do not need primary and foriegn key relationship. Any help would be really appreciated
This is my controller
public function Task(){
$data['cname'] = $this->welcome4->show_students3();
$data['projects'] = $this->welcome4->show_students();
$data['employee'] = $this->welcome4->show_students2();
$this->load->view('template/navigation');
$this->load->view('template/sideNav');
$this->load->view('template/header');
$this->load->view('Task',$data);
$this->load->view('template/footer');
}
This is my model
function show_students2(){
$query = $this->db->get('employee');
$query_result = $query->result();
return $query_result;
}
function show_students3(){
$query = $this->db->get('clientdetails');
$query_result = $query->result();
return $query_result;
}
function show_students4(){
$query = $this->db->get('task');
$query_result = $query->result();
return $query_result;
}
This is my view
<div class="form-group">
<label>Select Project</label>
</div>
<div class="form-group">
<select name="projectname" class="input form-control">
<option value="none" selected="selected">Select Project</option>
<?php foreach($projects as $s):?>
<option value="<?php echo $s->projectname?>"><?php echo $s->projectname?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Select Client</label>
<select name="cname" class="input form-control">
<option value="none" selected="selected">Select client</option>
<?php foreach($cname as $s):?>
<option value="<?php echo $s->cname?>"><?php echo $s->cname?></option>
<?php endforeach;?>
</select>
</div>
<div class="form-group">
<label>Select Employee</label>
</div>
<div class="form-group">
<select name="employee" class="input form-control">
<option value="none" selected="selected">Select Employee</option>
<?php foreach($employee as $s):?>
<option value="<?php echo $s->employee?>"><?php echo $s->employee?></option>
<?php endforeach;?>
</select>
</div>
This loads all projects, clients, employee in the database.But now I want when project is selected in the first drodown, second dropdown should show only relevant clients and employees to it. Not all of them
Lets consider this will be your Projects select box, in which you are loading data dynamically on page load with php.
<select name="projectname" id="projectname"></select>
Tasks select box.
<select name="tasks" id="tasks"></select>
Inside your controller add below mentioned code. This function will be used for get data from ajax call.
public function getTasks() {
$Id = $this->input->post('project_id');
if ($Id):
$this->load->model('Task_model', 'Tasks', TRUE);
$data = $this->Tasks->getProjectTasks($Id);
if ($data):
$result['status'] = true;
$result['records'] = $data;
endif;
else:
$result['status'] = false;
endif;
echo json_encode($fdata);
}
Inside model please add this function. Which will fetch data from DB
ans pass it to controller back.
public function getProjectTasks($id = null) {
if ($id):
$this->db->select('id,task');
$this->db->where('project_id', $id);
$this->db->where('status', TRUE);
$query = $this->db->get('tasks');
$records = $query->result();
if ($records):
return $records;
else:
return false;
endif;
else:
return false;
endif;
}
And finally in you View file please add below function.
$(document).on('#projectname', 'change', function() {
var projectId = $(this).val();
$.ajax({
type: 'POST',
url: 'URL',
data: {project_id: projectId},
dataType: "json",
beforeSend: function() {
$('#tasks')
.empty()
.append('<option selected="selected">Select Task</option>');
},
success: function(data) {
if (data.status) {
$.each(data.records, function(i, item) {
$('#tasks').append($('<option>', {
value: item.value,
text: item.text
}
));
});
} else {
$('#tasks')
.empty()
.append('<option selected="selected">No Task available</option>');
}
}
});
});

Array to string conversion on creating chained combobox with codeigniter

i'm trying to create a chained combobox (2 combobox) with codeigniter, the result is ok but when i inspect it with dev tools on chrome show:
array to string conversion
and i don't know how to solve it.
Here's my code:
Controller:
public function create()
{
$this->data['get_all_data'] = $this->Category_model->getkat();
$this->load->view('back/tool/tool_add', $this->data);
}
function get_subkat()
{
$id_kat = $this->input->post('id_kat');
$datasubkat = $this->Category_model->getdatasubkat($id_kat);
$this->data .= "<option value=''>-- CHOOSE --</option>";
foreach($datasubkat as $data_subkat)
{
$this->data .= "<option value='$data_subkat[id_subkat]'>$data_subkat[nama_subkat]</option>";
}
echo $this->data;
}
Model:
function getkat()
{
$result = $this->db->get($this->table);
if($result->num_rows() > 0)
{
return $result->result_array();
}
else
{return array();}
}
function getdatasubkat($id_kat)
{
$this->db->where('id_kat', $id_kat);
$result = $this->db->get('subkategori');
if($result->num_rows() > 0)
{
return $result->result_array();
}
else
{return array();}
}
View:
<script type="text/javascript">
$(document).ready(function(){
$("#kat").change(function(){
var id_kat = $("#kat").val();
$.ajax({
type: 'POST',
url: "<?php echo base_url('admin/tool/get_subkat'); ?>",
data:"id_kat="+id_kat,
success: function(data) {
$("#subkat").html(data);
}
});
});
});
</script>
<div class="row">
<div class="col-xs-6"><b>Category</b>
<select name="kat" id="kat" class="form-control">
<option value="">-- CHOOSE --</option>
<?php
foreach($get_all_data as $category){
echo "<option value=".$category['id_kat'].">".$category['nama_kat']."</option>";
}
?>
</select>
</div>
<div class="col-xs-6"><b>Sub category</b>
<select name="subkat" id="subkat" class="form-control">
<option value="">-- CHOOSE --</option>
</select>
</div>
</div>
Any help will be so appreciated, thank you

How to use AJAX to populate state list depending on Country list?

I have the code below that will change a state dropdown list when you change the country list.
How can I make it change the state list ONLY when country ID number 234 and 224 are selected?
If another country is selected it should be change into this text input box
<input type="text" name="othstate" value="" class="textBox">
The form
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
The javascript
<script>
function getState(countryId)
{
var strURL="findState.php?country="+countryId;
var req = getXMLHTTP();
if (req)
{
req.onreadystatechange = function()
{
if (req.readyState == 4)
{
// only if "OK"
if (req.status == 200)
{
document.getElementById('statediv').innerHTML=req.responseText;
} else {
alert("There was a problem while using XMLHTTP:\n" + req.statusText);
}
}
}
req.open("GET", strURL, true);
req.send(null);
}
}
</script>
Just check the countryId value before you do the AJAX request and only perform the request if the countryId is in the allowable range. In the case where the countryId doesn't match, I would hide the select (probably clear it's value, too) and show an already existing input that was previously hidden. The reverse should be done if an allowable country is chosen.
jQuery example below:
<form method="post" name="form1">
<select style="background-color: #ffffa0" name="country" onchange="getState(this.value)">
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" value="" class="textBox" style="display: none;">
</form>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
I think the simple thing to do is to provide a state dropdown and a text entry box with different ids. Set the display of both to none and then you just need to surround your contents of getState() with
if (countryId == 233 || countryId == 234) {
/* Ajax state population here */
dropdownId.display = 'block';
textEntryId.display = 'none';
}
else {
textEntryId.display = 'block';
dropdownId.display = 'none';
}
(where dropdownId and textEntryId are the ids of the relevant UI components) so you enable/display the display for the state dropdown or the text entry upon selection.
JQuery is all well and good, but I wouldn't introduce it just to solve this problem.
EDIT: here is a solution that works quite well for the task, adapting the lines of Tvanfosson:
<script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js">
</script>
<script>
$(function() {
$('#country').change( function() {
var val = $(this).val();
if (val == 223 || val == 224) {
$('#othstate').val('').hide();
$.ajax({
url: 'findState.php',
dataType: 'html',
data: { country : val },
success: function(data) {
$('#state').html( data );
}
});
}
else {
$('#state').val('').hide();
$('#othstate').show();
}
});
});
</script>
<select style="background-color: #ffffa0" name="country" id=country >
<option>Select Country</option>
<option value="223">USA</option>
<option value="224">Canada</option>
<option value="225">England</option>
<option value="226">Ireland</option>
</select>
<select style="background-color: #ffffa0" name="state">
<option>Select Country First</option>
</select>
<input type="text" name="othstate" id=othstate value="" class="textBox" style="display: none;">
As you can see, I eliminated the <form> element which is not absolutely necessary but can be added (and then has to be used properly in case JS is deactivated at the users end. See
here.
I also eliminated the onchange event which is being replaced by the 'change()` jquery function.
**index.html**
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Populate City Dropdown Using jQuery Ajax</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("select.country").change(function(){
var selectedCountry = $(".country option:selected").val();
$.ajax({
type: "POST",
url: "ajaxServer.jsp",
data: { country : selectedCountry }
}).done(function(data){
$("#response").html(data);
});
});
});
</script>
<style>
select { width: 10em }
</style>
</head>
<body>
<form>
<table>
<tr>
<td> <label>Country:</label></td>
<td> <select class="country">
<option>Select</option>
<option value="usa">United States</option>
<option value="india">India</option>
<option value="uk">United Kingdom</option>
</select>
</td>
</tr>
<tr><td >
<label>States:</label></td>
<td> <select id="response">
<option>Select State</option>
</select>
</td></tr>
</table>
</form>
</body>
</html>
**ajaxServer.jsp**
<option>Select State</option>
<%
String count=request.getParameter("country");
String india[]={"Mumbai", "New Delhi", "Bangalore"};
String usa[]={"New Yourk", "Los Angeles","California"};
String uk[]={"London", "Manchester", "Liverpool"};
String states[];
if(count.equals("india"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+india[i]+"</option>");
}
}
else if(count.equals("usa"))
{
for(int i=0;i<usa.length;i++)
{
out.print("<option>"+usa[i]+"</option>");
}
}
else if(count.equals("uk"))
{
for(int i=0;i<=2;i++)
{
out.print("<option>"+uk[i]+"</option>");
}
}
%>
VK API just select country , get it id and select city from
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.0/jquery.min.js"></script>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
var $j = jQuery.noConflict();
var _getCountry = function() {
$j.ajax({
url: "http://api.vk.com/method/database.getCountries",
data: {
'v': 5.5,
'need_all': 0,
'code' : 'RU,UA,BY,KZ,KG,LV,EE'
// 'count': 10
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each country");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
country_options.push(newOption);
});
document.getElementById('countrylist').innerHTML = country_options;
}
});
}
var _getCity = function(country_id) {
$j.ajax({
url: "http://api.vk.com/method/database.getCities",
data: {
'v': 5.61,
'need_all': 0,
'country_id': country_id
},
dataType: 'jsonp',
success: function(data, status) {
if (status !== 'success') {
return false;
}
console.log(data.response, status);
$j.each(data.response.items, function(i, item) {
console.log("each city");
var newOption = '<option id="' + item.id + '" value="' + item.title + '">' + item.title + '</option>';
city_options.push(newOption);
});
document.getElementById('citylist').innerHTML = city_options;
}
});
}
var city_options = [];
var country_options = [];
$j(document).ready(function () {
_getCountry();
$j('#country').on('input',function() {
var opt = $j('option[value="'+$j(this).val()+'"]');
var countryid = opt.attr('id');
_getCity(countryid);
});
});
</script>
<div class="form-group">
<label class="col-lg-4 control-label">Страна:</label>
<div class="col-lg-8">
<div class="controls">
<input name="country" list="countrylist" id="country" class="form-control" />
<datalist id="countrylist">
</datalist>
</div>
</div>
</div>
<div class="form-group">
<label class="col-lg-4 control-label">Город:</label>
<div class="col-lg-8">
<input name="city" list="citylist" id="city" class="form-control"/>
<datalist id="citylist">
</datalist>
</div>
</div>
////////////////// connection file con.php rishabh
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
$conn = mysql_connect($dbhost, $dbuser, $dbpass);
if(! $conn ) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db( 'testajax' );
?>
/////////////////////////// index.php rishabh
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<?php
include('con.php');
?>
<form>
<div class="frmDronpDown">
<div class="row">
<table><tr><td><label>Country:</label><br/>
<select name="country" id="country" data-name="country" class="demoInputBox" onChange="getCountry(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct country FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['country']; ?>"><?php echo $result['country']; ?></option>
<?php
}
?>
</select> </td>
<td>
<label>Phone:</label><br/>
<select name="phone" id="phone" data-name="phone" class="demoInputBox" onChange="getPhone(this.value);">
<option value="">Select Country</option>
<?php
$sql = mysql_query("SELECT distinct phone FROM statecont ");
while($result=mysql_fetch_array($sql)){
?>
<option value="<?php echo $result['phone']; ?>"><?php echo $result['phone']; ?></option>
<?php
}
?>
</select>
</td></tr></table>
</div>
<div id="state-list"></div>
</div>
</form>
<script>
function getCountry(val) {
var dataname = $('#country').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
function getPhone(val) {
var dataname = $('#phone').attr('data-name');
console.log(dataname);
$.ajax({
type: "POST",
url: "data.php",
data: {
value_name: val,
colomn_name: dataname
},
success: function (data){
$("#state-list").html(data);
}
});
}
</script>
// ////////////////////data file data.php rishabh
<?php
$val = $_POST["value_name"];
$colomn = $_POST["colomn_name"];
include('con.php');
$sql_aa = mysql_query("SELECT * FROM statecont where ".$colomn."='$val'"); ?>
<table>
<tr><td>State</td><td>Countery</td></tr>
<?php while($result_aa=mysql_fetch_array($sql_aa)){ ?>
<tr><td><?php echo $result_aa['state']; ?></td><td><?php echo $result_aa['country']; ?></td></tr>
<?php } ?>
</table>

Resources