Dependent dropdown using ajax in laravel - ajax

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);
}

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>);
});

How to display data to textfield from combo selection in laravel

I'd like to display data to textfield based on combo/drop box selection in laravel 5.8. then save the data. is there complete tutorial how to do it from model, view and controller.
In Customer Controller
public function create()
{
$customer= Customer::all();
return view('Customer.create', compact('Customer'));
}
in view create.blade
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>CUSTOMER</strong>
<select type="text" class="form-control" name="kde_cust" id="cde_customer" required>
<option value=""> -- PICK CUST-- </option>
#foreach($cust as $cust)
<option value="{{ $cust->cde_cust }}" selected>{{ $cust->nme_customer }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-xs-12 col-sm-12 col-md-12">
<div class="form-group">
<strong>NAME</strong>
<input type="text" name="cust_name" id="cust_name" class="form-control" value="{{ $cust->nme_customer }}">
</div>
</div>
This should helps:
Create a route to get the user address:
Route::get('user-address/{user_id}','YourController#method')->name('user.address');
Your controller method should look like this:
public function yourFunction($cde_customer)
{
$customer = Customer::where('cde_customer', $cde_customer)->first();
$address = $customer->address;
return response()->json([
'address' => $address,
]);
}
Add this script to your blade:
$("#cde_customer").on('change', function(){
var user_id = $(this).val();
$.ajax({
url: '/user-address/' + user_id,
method: 'GET',
success: function(response){
$("#textfield").html(response.address);
}
});
});
Hope it helps.

How to create dynamic select option in laravel?

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);

Codeigniter Mysql Ajax Pagination sort and search

I have to do a codeigniter crud operation. But now i want to add pagination search and sort for that.I used lots of tutorials to do that. But i can't understand. To anyone who knows please help me to do that. Thank you.
controller
class User_controller extends CI_Controller {
public function __construct() {
parent::__construct();
$this->load->model('user_model');
$this->load->library('form_validation');
}
// load user_list view
public function index()
{
$this->load->view('admin_include/header');
$this->load->view('admin_pages/user_list');
}
// show all the users in view
public function fillgrid(){
$this->user_model->fillgrid();
}
function fetch_record(){
$this->user_model->fetch_record();
}
// validate and insert new user data
public function create(){
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
echo'<div class="alert alert-danger">'.validation_errors().'</div>';
exit;
}
else{
$this->user_model->create();
}
}
// edit user
public function edit(){
$id = $this->uri->segment(3);
$this->db->where('id',$id);
$data['query'] = $this->db->get('user');
$data['id'] = $id;
$this->load->view('admin_pages/user_edit', $data);
}
// update validation
public function update(){
$res['error']="";
$res['success']="";
$this->form_validation->set_rules('firstname', 'First Name', 'required');
$this->form_validation->set_rules('lastname', 'Last Name', 'required');
$this->form_validation->set_rules('email', 'Email', 'required|valid_email');
$this->form_validation->set_rules('contact_no', 'Contact Number', 'required|numeric|max_length[10]|min_length[10]');
if ($this->form_validation->run() == FALSE){
$res['error']='<div class="alert alert-danger">'.validation_errors().'</div>';
}
else{
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'));
$this->db->where('id', $this->input->post('hidden'));
$this->db->update('user', $data);
$res['success'] = '<div class="alert alert-success">One record updated Successfully</div>';
}
header('Content-Type: application/json');
echo json_encode($res);
exit;
}
//delete user
public function delete(){
$id = $this->input->POST('id');
$this->db->where('id', $id);
$this->db->delete('user');
echo'<div class="alert alert-success">One record deleted Successfully</div>';
exit;
}
model
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class User_model extends CI_Model {
public function fillgrid(){
$this->db->order_by("id", "desc");
$data = $this->db->get('user');
foreach ($data->result() as $row){
$edit = base_url().'index.php/user_controller/edit/';
$delete = base_url().'index.php/user_controller/delete/';
echo "<tr>
<td>$row->firstname</td>
<td>$row->lastname</td>
<td>$row->email</td>
<td>$row->contact_no</td>
<td>$row->address</td>
<td>$row->created</td>
<td><a href='$edit' data-id='$row->id' class='btnedit' title='edit'><i class='glyphicon glyphicon-pencil' title='edit'></i></a> <a href='$delete' data-id='$row->id' class='btndelete' title='delete'><i class='glyphicon glyphicon-remove'></i></a></td>
</tr>";
}
exit;
}
public function create(){
$data = array('firstname'=> $this->input->post('firstname'),
'lastname'=> $this->input->post('lastname'),
'email'=>$this->input->post('email'),
'contact_no'=>$this->input->post('contact_no'),
'address'=>$this->input->post('address'),
'created'=>date('d/m/y'));
$this->db->insert('user', $data);
echo'<div class="alert alert-success">One record inserted Successfully</div>';
exit;
}
private function edit(){}
private function delete(){}
//2015.7.26
//set table name to be used by all functions
var $table = 'user';
function fetch_record($limit, $start)
{
$this->db->limit($limit, $start);
$query = $this->db->get($this->user);
return ($query->num_rows() > 0) ? $query->result() : FALSE;
}
function record_count()
{
return $this->db->count_all_results('user');
}
//2015.7.26
}
//2015.7.26
public function pagination(){
$page_number = $this->input->post('page_number');
$item_par_page = 2;
$position = ($page_number*$item_par_page);
$result_set = $this->db->query("SELECT * FROM user LIMIT ".$position.",".$item_par_page);
$total_set = $result_set->num_rows();
$page = $this->db->get('user') ;
$total = $page->num_rows();
//break total recoed into pages
$total = ceil($total/$item_par_page);
if($total_set>0){
$entries = null;
// get data and store in a json array
foreach($result_set->result() as $row){
$entries[] = $row;
}
$data = array(
'TotalRows' => $total,
'Rows' => $entries
);
$this->output->set_content_type('application/json');
echo json_encode(array($data));
}
exit;
}
view
<div class="well">
<form class="form-inline" role="form" id="frmadd" action="<?php echo base_url() ?>index.php/user_controller/create" method="POST">
<!--First Name-->
<div class="form-group">
<label class="sr-only" for="firstname">First Name</label>
<input type="text" name="firstname" class="form-control" id="firstname" placeholder="First name">
</div>
<!--/First Name-->
<!--Last Name-->
<div class="form-group">
<label class="sr-only" for="lastname">Last Name</label>
<input type="text" name="lastname" class="form-control" id="lastname" placeholder="Last Name">
</div>
<!--/Last Name-->
<!-- email-->
<div class="form-group">
<div class="input-group">
<div class="input-group-addon">#</div>
<input class="form-control" name="email" type="email" placeholder="Enter email">
</div>
</div>
<!-- email-->
<!--Contact-->
<div class="form-group">
<label class="sr-only" for="contact_no">Contact</label>
<input type="text" class="form-control" name="contact_no" id="contact_no" placeholder="contact number">
</div>
<!--/Contact-->
<!--Address-->
<div class="form-group">
<label class="sr-only" for="address">Address</label>
<input type="text" name="address" class="form-control" id="exampleInputPassword2" placeholder="Address">
</div>
<!--/Address-->
<!--submit-->
<input type="submit" class="btn btn-success" id="exampleInputPassword2" value="submit">
<!--/submit-->
</div>
</form>
</div>
<table class="table">
<thead><tr><th>First Name</th><th>Last Name</th><th>Email</th><th>Contact</th><th>Address</th><th>created</th><th>Action</th></tr></thead>
<tbody id="fillgrid">
</tbody>
<tfoot></tfoot>
</table>
<!-- //2015.7.26-->
<div class="row clear-fix">
<div class="col-md-4 pull-right">
<button id="previous" class="btn btn-sm btn-primary">Previous</button>
<lable>Page <lable id="page_number" name="page_number" ></lable> of <lable id="total_page" name="total_page"></lable></lable>
<button id="next" class="btn btn-sm btn-primary">Next</button>
</div>
</div>
<div style="text-align: center">
<!--//2015.7.26-->
</div>
</div>
</div>
<script>
$(document).ready(function (){
//fill data
var btnedit='';
var btndelete = '';
fillgrid();
// add data
$("#frmadd").submit(function (e){
e.preventDefault();
$("#loader").show();
var url = $(this).attr('action');
var data = $(this).serialize();
$.ajax({
url:url,
type:'POST',
data:data
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
});
function fillgrid(){
$("#loader").show();
$.ajax({
url:'<?php echo base_url() ?>index.php/user_controller/fillgrid',
type:'GET'
}).done(function (data){
$("#fillgrid").html(data);
$("#loader").hide();
btnedit = $("#fillgrid .btnedit");
btndelete = $("#fillgrid .btndelete");
var deleteurl = btndelete.attr('href');
var editurl = btnedit.attr('href');
//delete record
btndelete.on('click', function (e){
e.preventDefault();
var deleteid = $(this).data('id');
if(confirm("are you sure")){
$("#loader").show();
$.ajax({
url:deleteurl,
type:'POST' ,
data:'id='+deleteid
}).done(function (data){
$("#response").html(data);
$("#loader").hide();
fillgrid();
});
}
});
//edit record
btnedit.on('click', function (e){
e.preventDefault();
var editid = $(this).data('id');
$.colorbox({
href:"<?php echo base_url()?>index.php/user_controller/edit/"+editid,
top:50,
width:500,
onClosed:function() {fillgrid();}
});
});
});
}
});
</script>
i think you have to check your db field name it will work definitely you are missing some db field name...

Resources