How to create dynamic select option in laravel? - ajax

I want to generate a list on items in a drop down based on a previous choice from another select. All items ar in the database.
Here is what I did:
Javascript:
$(document).ready(function () {
$(document).on('change', '#province_name', function() {
var province_id = $(this).val();
var div = $(this).parent();
var op = " ";
$.ajax({
type: 'get',
url: '{!!URL::to('admin/findIDProvince')!!}',
data: {'id':province_id},
success: function(data){
for (var i = 0; i < data.length; i++){
op += '<option value="'+data[i].id+'">'+data[i].city_name+'</option>';
}
div.find('#city_name').html(" ");
div.find('#city_name').append(op);
},
error: function(){
console.log('success');
},
});
});
});
Routes (web.php):
Route::namespace('Admin')->prefix('admin')->middleware('auth')->group(function (){
$this->get('/findIDProvince', 'SchoolsListController#findIDProvince');
});
Controller (Admin/SchoolsListController.php):
public function findIDProvince(Request $request)
{
$data = City::select('city_name', 'id')->where('province_id', $request->id)->take(100)->get();
return response()->json($data);
}
HTML (view.blade.php)
<div class="form-group">
<label class="col-md-3" for="province_name">province_name</label>
<div class="col-md-9">
<select id="province_name" name="province_name" class="form-control col-md-12" required>
#foreach($province_names as $province_name)
<option value="{{ $province_name->id }}">{{ $province_name->province_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-3" for="city_name">city_name</label>
<div class="col-md-9">
<select id="city_name" name="city_name" class="form-control col-md-12" required>
</select>
</div>
</div>
What am I doing wrong?

You are using
div.find('#city').html(" ");
div.find('#city').append(op);
but in your blade you have
id = city_name
Use:
div.find('#city_name').html(" ");
div.find('#city_name').append(op);

Related

laravel dynamic drop down not giving value

im using ajax for laravel dropdown it was working but when i tiring to submit form it was giving id number
im getting right input in dropdown field when i try to submit page it was giving id number instead of dropdown value
i what to get value of MS OFFICE AND 1000 BUT IT STORING IN DATA BASCE {COURES TYPE C_1402:}
{ COURSE PRICE C_1402:}
my view
my network tab showing this id
my view page
<div class="col-md-4">
<div class="form-group">
<label for="location1">Course Type :<span class="danger">*</span> </label>
<select class="custom-select form-control required" name="student_course" id="student_courses" name="location" required>
<option value="">Select Course</option>
#foreach ($course_name as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<label for="videoUrl1">Course Price :</label>
<select name="course_Price" id="course_Prices" class="form-control dynamic" data-dependent="course_Price">
<option value=""></option>
</select>
</div>
</div>
ajax
<script type="text/javascript">
$(document).ready(function() {
$('#student_courses').on('change', function() {
var stateID = $(this).val();
if(stateID) {
$.ajax({
url: '/Student_Course_get_price/'+stateID,
type: "GET",
dataType: "json",
success:function(data) {
$('#course_Prices').empty();
$.each(data, function(key, value) {
$('#course_Prices').append('<option value="'+ key +'">'+ value +'</option>');
});
}
});
}else{
$('#course_Prices').empty();
}
});
});
</script>
my controller
public function Student_Course_get()
{
$course_name = DB::table("courses")->pluck('COURSE_NAME','COURSE_NAME_id');
return view('Admin/Student.Student_enrollment',compact('course_name'));
}
public function Student_Course_get_price($COURSE_NAME_id)
{
$cities = DB::table("courses")
->where("C_id",$COURSE_NAME_id)
->pluck('COURSE_AMOUNT','C_id');
return json_encode($cities);
}
The value of your select option is a key not the value you see in the UI which will presumably be the 'C_id'.
Change your
$('#course_Prices').append('<option value="'+ key +'">'+ value +'</option>');
To
$('#course_Prices').append('<option value="'+ value +'">'+ value +'</option>');

ajax in laravel not showing. but in console , i can see the get url

I am making 2 dropdown which is the second one is dependent from first one. And here is my view code:
<div class="col-lg-6 col-md-6 col-sm-12">
<div class="form-group">
<label class="form-label">General</label>
<select class="form-control formselect required"
placeholder="Select Category" id="sub_category_name">
<option value="0" disabled selected>Select
Main Category*</option>
#foreach($data as $categories)
<option value="{{ $categories->id }}">
{{ ucfirst($categories->catname) }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-lg-6 col-md-6 col-sm-12">
<div class="form-group">
<label class="form-label">Sub</label>
<select class="form-control formselect required"
placeholder="Select Sub Category" id="sub_category">
</select>
</div>
</div>
Then here is my code in controller :
public function index(Request $request)
{
$data = DB::table('cats')->get();
return view('admin.genc.gencEntry')->with('data', $data);
}
public function subcat($id){
echo json_encode(DB::table('subcats')->where('catid', $id)->get());
}
And ajax is here:
<script>
$(document).ready(function () {
$('#sub_category_name').on('change', function () {
let id = $(this).val();
$('#sub_category').empty();
$('#sub_category').append(`<option value="0" disabled selected>Processing...</option>`);
$.ajax({
type: 'GET',
url: 'subcat/' + id,
success: function (response) {
var response = JSON.parse(response);
console.log(response);
$('#sub_category').empty();
$('#sub_category').append(`<option value="0" disabled selected>Select Sub Category*</option>`);
response.forEach(element => {
$('#sub_category').append(`<option value="${element['id']}">${element['subcatname']}</option>`);
});
}
});
});
});
</script>
But when i select a option from first dropdown, second one is not showing anything.
But i can see XHR finished loading: GET "http://www.example.com:8000/genc/subcat/7" in my console.
Can someone tell me where is the error causing the empty dropdown?
It's look like issue with your loop syntax, use it like
$.each(response, function(key,element) {
$('#sub_category').append(<option value="${element['id']}">${element['subcatname']}</option>);
});

Dependent dropdown using ajax in laravel

I have a dropdown for students_id. Now I want to track the student name and class from another table when someone select any student id. I did something for that using ajax. Its not showing me any error in the console but just giving me null array and I think thats the problem related to the query. You can check my code below. :)
//Controller
public function create()
{
$students = Student::pluck('student_id', 'id')->all();
return view('admin.reports.create', compact('students'));
}
public function reportsAjax(Request $request) {
$students = DB::table("students")->where("student_id", $request->student_id)->pluck("student_id","id");
return json_encode($students);
}
//View and Ajax
<div class="form-group">
<label for="title">Select Student <span style="color: red">*</span></label>
<select name="student_id" class="form-control bg-dark text-white" >
<option>Select Student</option>
#foreach ($students as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label class="control-label">Student Full Name <span style="color: red">*</span></label>
<input name="std_name" type="text" required class="form-control" />
</div>
<div class="form-group">
<label class="control-label">Class <span style="color: red">*</span></label>
<input name="std_class" type="text" required class="form-control" />
</div>
<script type="text/javascript">
$(document).ready(function() {
$('select[name="student_id"]').on('change', function() {
var studentInfo = $(this).val();
if(studentInfo) {
$.ajax({
url: '/reports/ajax/'+studentInfo,
type: "GET",
dataType: "json",
success:function(data) {
$('input[name="std_name"]').empty();
$.each(data, function(key, value) {
$('select[name="std_name"]').append('<input value="'+ key +'">'+ value +'/>');
});
}
});
}else{
$('select[name="std_name"]').empty();
}
});
});
</script>
//Routes
Route::get('reports/ajax/{id}',array('as'=>'reports.ajax','uses'=>'ReportController#reportsAjax'));
Route::resource('admin/reports', 'ReportController', ['names'=>[
'index'=>'admin.reports.index',
'create'=>'admin.reports.create',
]]);
Try this for your queries:
public function create()
{
$students = Student::all()->only(['student_id', 'id']);
return view('admin.reports.create', compact('students'));
}
public function reportsAjax(Request $request)
{
$students = DB::table('students')->where('student_id', $request->student_id)->only(['student_id','id']);
return response()->json($students, 200);
}

Ajax query returning correct value in console log, but not showing in the view

This is my html code.
<div class="form-group row add">
<label class="control-label col-sm-2" for="division_id">Division Name:</label>
<div class="col-sm-10">
<select name="district_id" id ="district_id" class="selectdistrict">
<option value="">--Select district--</option>
#foreach($atmdistrict as $cat)
<option value="{{$cat->id}}">{{$cat->name}}</option>
#endforeach
</select>
</div>
</div>
<div class="form-group row add">
<label class="control-label col-sm-2" for="thana_id">Thana Name:</label>
<div class="col-sm-10">
<select name="thana_id" class="thananame" id ="thana_id" >
<option value="0" disabled="true" selected="true">Thana Name</option>
</select>
</div>
</div>
This is my ajax query for dependent dropdown.
$(document).ready(function(){
$(document).on('change','.selectdistrict',function(){
console.log("hmm its change");
var district_id=$(this).val();
console.log(district_id);
var div=$(this).parent();
var op=" ";
$.ajax({
type:'get',
url:'{!!URL::to('findThanaName')!!}',
data:{'id':district_id},
success:function(data){
console.log('success');
console.log(data);
//console.log(data.length);
op+='<option value="0" selected disabled>chose thana</option>';
for(var i=0;i<data.length;i++){
op+='<option value="'+data[i].id+'">'+data[i].name+'</option>';
console.log(data[i].name);
}
div.find('.thananame').html(" ");
// console.log( div.find('.name').html(" "));
div.find('.select').append(op);
//console.log( div.find('.select').append(op));
},
error:function(){
console.log('error');
}
});
});
});
The console log is showing no error, and is returning the correct data. However, the drop down menu is not showing any data. I can't figure out where I am going wrong.
screenshot of the program running
try to change :
div.find('.select').append(op);
by :
$("#thana_id").html(op);

Send form data via AJAX to multiple PHP files

So, i have no clue if what i want to do is even possible, but i tried and failed ;P
<script>
$("#submitdata").submit(function()
{
var datefrom=document.getElementById( "datefrom" );
var dateto=document.getElementById( "dateto" );
var dropdown=document.getElementById( "dropdown" ).value;
alert (dropdown);
if (dropdown === "0") {
alert ("Please choose first!");
} else if (dropdown === "1") {
$.ajax({
type: 'post',
url: 'showData.php',
data: {
datefrom: datefrom,
dateto: dateto,
choice: dropdown
},
success: function () {
$('#inner').load('#inner');
}
});
return false;
} else if (dropdown === "2") {
} else if (dropdown === "3") {
} else if (dropdown === "4") {
}
});
</script>
<form method="post" id="submitdata" name="submitdata">
<div class="row uniform">
<div class="12u 12u$">
<input type="text" name="datefrom" id="datefrom" value="" placeholder="From" />
</div>
<div class="12u 12u$">
<input type="text" name="dateto" id="dateto" value="" placeholder="To" />
</div>
<div class="12u$">
<div class="select-wrapper">
<select name="dropdown" id="dropdown">
<option value="0">- Choose -</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
</select>
</div>
</div>
<div class="12u$">
<ul class="actions">
<li><input type="submit" id="btnSubmit" value="Submit" class="special" /></li>
<li><input type="reset" value="Reset" /></li>
</ul>
</div>
</div>
</form>
I want to send the data to different files, depending on what the user chooses in the form dropdown (if that is possible).
I get the alerts and everything is fine but it just jumps into the other "elseif's" even tho the value of dropdown is "0".
Any idea how to solve this?
I found the solution eventually:
if(!datumvon.value){
alert("Watch out");
}
else if(dropdown === "0"){
alert("Do Step 1 first");
}else if(dropdown >= "1") {
$.ajax({
type: 'post',
url: 'showData.php',
data: {
datumvon: datumvon,
datumbis: datumbis,
dropdown: dropdown
},
success: function () {
$('#inner').load('#inner');
}
});
}else {
alert("Error");
}
return false;
The problem was some kind of syntax error in the javascript part. Thanks for the help

Resources