I am trying to get dependant select items using ajax call. After selecting 'class' it should show the related 'groups'. But, I am getting 500 internal server error on my console. Would someone help me please to get the expected result?
admission-form.blade.php -
<form action="{{ route('admin.students.admission') }}" method="POST" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="row">
<div class="col-sm-6">
<div class="form-group {{ $errors->has('first_admission_class') ? 'has-error' : '' }}">
<select class="form-control" name="first_admission_class" id="first_admission_class">
<option value="">Select Class</option>
#foreach($classes as $class)
<option value="{{ $class->id }}" {{ (old("first_admission_class") == $class->id ? "selected":"") }}>{{ $class->class_name }}</option>
#endforeach
</select>
</div>
</div>
<div class="col-sm-6">
<div class="form-group {{ $errors->has('first_admission_class_group') ? 'has-error' : '' }}">
<select class="form-control" name="first_admission_class_group">
</select>
</div>
</div>
</div>
</form>
Script for Ajax call:
<script>
$('#first_admission_class').on('change', function(e){
console.log(e);
var class_id = e.target.value;
$.get('http://localhost/school/public/admin/ajax-group/' + class_id, function(data){
console.log(data);
});
});
</script>
web.php -
Route::group(['prefix' => 'admin', 'as' => 'admin.', 'middleware' => 'auth:admin'], function () {
Route::get('ajax-group/{id}', function(){
$class_id = Input::get('class_id');
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
});
your route is look like this, when we add param in route they accessible via function param. i hope it works for you.
Route::get('ajax-group/{id}', function($id){
$groups = AvailableclassGroup::where('availableclass_id', '=', $id)->get();
return Response::json($groups);
});
});
you can check laravel doc Laravel route doc
if still it didnot work then
add csrf token, like this in head of your html layout
<meta name="csrf-token" content="{{ csrf_token() }}">
and make your ajax call like this
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
})
$.ajax({
type: 'get',
url: '/ajax-group/'+ class_id,
dataType: 'json',
success: function (data) {
},
error: function (data) {
console.log('Error:', data);
}
});
Your wildcard its named id and you are getting as class_id so change :
And make sure your route its named as admin.students.admission
Route::get('ajax-group/{id}', function(){
$class_id = Input::get('id');
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
})->name('admin.students.admission');
And make sure you have imported the classes on route file.
as I saw, you're not sending data, so you can't say $class_id = Input::get('id');. You have id parameter in your url, just use it.
Route::get('ajax-group/{id}', function($class_id){
$groups = AvailableclassGroup::where('availableclass_id', '=', $class_id)->get();
return Response::json($groups);
});
Related
Here is my output. When user select the site, the list of controller will display. My problems is when user select the site, the list of controller does not displayed.
Controller:
public function index()
{
$sites = Sites :: pluck ('sites_id' ,'site_code' , 'site_name');
return view ('query.index',compact('sites'));
}
public function getController($sites_id){
$controllerData['data'] = device_profile::orderby("dvc_name","asc")
->select('id','dvc_name')
->where('sites',$sites_id)
->get();
return response()->json($controllerData);
}
View:
<div class="form-group">
<label class="control-label mb-10 text-left">Site:</label>
<select name="sites_id" class="form-control" required="">
#foreach ($sites as $site_code => $sites_id)
<option value="{{$sites_id}}"
{{ old('sites_id') == $sites_id ? 'selected' : '' }}>
{{ $site_code }}
</option>
#endforeach
</select>
#error('sites_id')
<span class="invalid-feedback" role="alert">
<strong>{{ $message }}</strong>
</span>
#enderror
</div>
<div class="form-group">
<label for="dvc_name">Select Controller:</label>
<select name="dvc_name" class="form-control" required="">
<option>--Controller List--</option>
</select>
</div>
<script type='text/javascript'>
$(document).ready(function(){
// Department Change
$('#sites_id').change(function(){
// Department id
var id = $(this).val();
// Empty the dropdown
$('#dvc_name').find('option').not(':first').remove();
// AJAX request
$.ajax({
url: 'getController/'+sites_id,
type: 'get',
dataType: 'json',
success: function(response){
var len = 0;
if(response['data'] != null){
len = response['data'].length;
}
if(len > 0){
// Read data and create <option >
for(var i=0; i<len; i++){
var sites_id = response['data'][i].sites_id;
var dvc_name = response['data'][i].dvc_name;
var option = "<option value='"+sites_id+"'>"+dvc_name+"</option>";
$("#dvc_name").append(option);
}
}
}
});
});
});
</script>
Web:
Route::get('query-index', 'QueryDataController#index')->name('query.index');
Route::get ('query-controller/getcontrollers/{sites_id}', 'QueryDataController#getControllers')->name('profile.getControllers');
Below is my database for sites and device profile:
Sites:
Device Profile:
I hope someone can help me to solve this problem. Thank you.
your URL in your ajax method is:
url: 'getController/'+sites_id,
And your route is :
Route::get ('query-controller/getcontrollers/{sites_id}', 'QueryDataController#getControllers')->name('profile.getControllers');
So you should change your ajax URL to this:
url: 'query-controller/getControllers/'+sites_id,
In this you have to call that url in ajax, url should be same as that you mention in Routes,
$('#sites_id').change(function(){
var site_id=this.value;
$.ajax({
siteid:site_id,
url : 'query-controller/getcontrollers/'+siteid,
})
})
In my Laravel-5.8, I passed data from controller to view using JSON.
I am using Laravel-5.8 for a web application project.
I am trying to make my dropdown load value on a textbox on change.
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$userEmployee = Auth::user()->employee_id;
$identities = DB::table('appraisal_identity')->select('id')->where('company_id', $userCompany)->where('is_current', 1)->first();
$child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first();
$parentid = DB::table('appraisal_goal_types')->select('parent_id')->where('company_id', $userCompany)->where('id',$request->id)->first();
if(empty($child))
{
abort(404);
}
$weightedscore = DB::table('appraisal_goals')->select(DB::raw("SUM(weighted_score) as weighted_score"))->where('appraisal_identity_id', $identities)->where('employee_id', $userEmployee)->where('parent_id', $parentid)->get();
$maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore->max_score,
'weightedscore' => $weightedscore
]);
}
I send the max_score and weighted_score as JSON.
route:
Route::get('get/findScore','Appraisal\AppraisalGoalsController#findScore')->name('get.scores.all'); view blade
<form action="{{route('appraisal.appraisal_goals.store')}}" method="post" class="form-horizontal" enctype="multipart/form-data">
{{csrf_field()}}
<div class="card-body">
<div class="form-body">
<div class="row">
<div class="col-12 col-sm-6">
<div class="form-group">
<label class="control-label"> Goal Type:<span style="color:red;">*</span></label>
<select id="goal_type" class="form-control" name="goal_type_id">
<option value="">Select Goal Type</option>
#foreach ($categories as $category)
#unless($category->name === 'Job Fundamentals')
<option hidden value="{{ $category->id }}" {{ $category->id == old('category_id') ? 'selected' : '' }}>{{ $category->name }}</option>
#if ($category->children)
#foreach ($category->children as $child)
#unless($child->name === 'Job Fundamentals')
<option value="{{ $child->id }}" {{ $child->id == old('category_id') ? 'selected' : '' }}> {{ $child->name }}</option>
#endunless
#endforeach
#endif
#endunless
#endforeach
</select>
</div>
</div>
<input type="text" id="max_score" class="form-control" >
<input type="text" id="weighted_score" class="form-control" >
</form>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('change', '#goal_type', function() {
var air_id = $(this).val();
var a = $(this).parent();
console.log("Its Change !");
var op = "";
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
// console.log("price");
console.log(data.maxscore);
console.log(data.weightedscore);
$('#max_score').val(data.maxscore);
$('#weighted_score').val(data.weightedscore);
},
error:function(){
}
});
});
});
</script>
When I click on the dropdown on change the max_score is working perfectly, but the weighted_score is having error:
GET http://localhost:8888/peopleedge/get/findScore?id=2 500 (Internal Server Error).
Then I got this on my console:
and the textbox:
I need the direct value to be displayed on the text and not the JSON object as shown in the diagram. For example, only 60 in the textbox.
How do I get this resolved?
Thank you.
$weightedscore is an object, so you should do the same for $weightedscore what you do for $maxscore: add the attribute and not the object to the response.
Change $weightedscore to $weightedscore->weighted_score in the return part.
return response()->json([
'maxscore' => $maxscore->max_score,
'weightedscore' => $weightedscore->weighted_score
]);
You can output $weightedscore before returning it by using var_dump($weightedscore); or print_r($weightedscore); and then you will see that it is an object having an attribute called weighted_score as stated in your SELECT ... as() part of your SQL statement.
since it is array hence it will be
$('#max_score').val(data.maxscore['maxscore']);
$('#weighted_score').val(data.weightedscore['weightedscore'][0]);
['weightedscore']=keyname that you gave on the controller
$.ajax({
type: 'get',
url: '{{ route('get.scores.all') }}',
data: { 'id': air_id },
dataType: 'json', //return data will be json
success: function(data) {
// console.log("price");
console.log(data.maxscore);
console.log(data.weightedscore);
$('#max_score').val(data.maxscore['maxscore']);
$('#weighted_score').val(data.weightedscore['weightedscore'][0]);
},
error:function(){
}
});
I have a users' data table and im trying to change role of them by populating roles from database to datatable. I use ajax to change the role and it works. but problem is value of selecting option from dropdown is not sent to database.
Herewith I attached my controller function view and ajax code.
Please advise me to solve this.
Controller:
public function changeRole(Request $request){
$id = Input::get('id');
$isAdmin = Input::get('isAdmin');
User::findOrFail($id)->update(['isAdmin'=>$isAdmin]);
}
Ajax :
$(document).ready(function(){
$('select').on('change' , function (event){
id = $(this).data('id');
isAdmin = $('#role').val();
//alert(role);
$.ajax({
type: 'POST',
url: SITE_URL + '/changeRole/',
data: {
'_token': $('input[name=_token]').val(),
'id': id,
'isAdmin': isAdmin
},
cache: false,
success: function(data) {
toastr.success('Admin Role Successfully Changed ! ', 'Congratulations', {timeOut: 5000});
//$('#example1').DataTable().ajax.reload();
},
error: function (jqXHR, exception) {
console.log(jqXHR);
toastr.error('Something Error !', 'Status not Changed!')
},
});
});
});
View :
<td>
<form method="post">
{{ csrf_field() }}
<div class="form-group">
<select class="form-control" data-id="{{$user->id}}" id="role" name="role">
<option value="0">Select a Role</option>
#foreach ($roles as $role)
<option #if($user->isAdmin==$role->id) selected #endif value="{{ $role->id }}">{{ $role->name }}</option>
#endforeach
</select>
</div>
</form>
</td>
Please see the user table view
First of all don't use Input::get('id') use $request->id and $request->isAdmin
Try dd($request->all()) at the very first line of you changeRole() method and check if you are getting the correct values every time.
Don't use $('select') give your select some id and use it as $('#myselect')
add var before you variable in jquery like var id=$() to keep it in local scope.
for reference must read this : https://www.tutorialspoint.com/What-is-the-difference-between-global-and-local-Variables-in-JavaScript
Don't use var id = $(this).data('id'); the .data() messes things up sometimes.
Use it as
var id = $(this).attr('data-id');
To get the value of selected roles use following:
var isAdmin = $(this).children("option:selected").val();
Hope this fixes many things.
I'm working on a screen with the following url http://localhost/npr/public/admin/athletes/test/143
On this screen, I've implemented the following dynamic droplist Ajax call that's not found:
$(document).ready(function() {
$('select[name="section"]').on('change', function() {
var sectionID = $(this).val();
if(sectionID) {
$.ajax({
url: './getSportPositions'+sectionID,
method: 'get',
//data: {"_token": $('#token').val()},
dataType: "json",
success:function(data) {
$('select[name="position"]').empty();
$('select[name="position"]').append('<option value="">'+ '-- Please choose one --' +'</option>');
$.each(data, function(i, position) {
$('select[name="position"]').append('<option value="'+position.name+'">'+ position.name +'</option>');
});
}
});
}else{
$('select[name="position"]').empty();
}
});
});
Route:
Route::get('getSportPositions{id}','HomeController#getSportPositions');
I've also tried with:
Route::get('/admin/athletes/test/getSportPositions{id}','HomeController#getSportPositions');
Is it due to athlete ID 143 in the calling URL? How do I fix this call?
It seems from the error that it's trying to access this route:
Route::get('/admin/athletes/test/{athlete}/', [
'uses' => 'HomeController#testAnAthlete',
'as' => 'admin.test_athlete'
]);
HTML:
<div class="form-group {{ $errors->has('position') ? ' alert alert-danger' : '' }}">
<label for="position" class="col-md-3 control-label">Position in Team</label>
<div class="col-md-6">
<select class="form-control" name="position" id="position">
#if (!$errors->has('position'))
<option selected value> -- select a team first -- </option>
#endif
</select>
</div>
#if ($errors->has('position'))
<span class="help-block">
<strong>{{ $errors->first('position') }}</strong>
</span>
#endif
</div>
When you are using Ajax you have to get url like
var APP_URL = $('meta[name="_base_url"]').attr('content');
also add this
<meta name="_base_url" content="{{ url('/') }}">
to head tag
then after you can use APP_URL
var url = APP_URL+"/getSportPositions/"+sectionID;
Additional from me. in laravel view :
<meta name="_base_url" content="{{ url('/') }}">
<meta name="csrf-token" content="{{ csrf_token() }}">
in addition to #Nikhil Radadiya answer, because using jquery mean you wait for page ready, you can use javascript :
var APP_URL = document.getElementsByTagName('meta')._base_url.content;
var APP_CSRF = document.querySelector("meta[name='csrf-token']").content; // javascript cannot use dash, else you can use csrf_token at meta name
then you can use in your ajax like :
$.ajax({
headers: {
'X-CSRF-TOKEN': APP_CSRF
},
url: APP_URL + '/your_ajax_path',
...
...
});
and make sure the url is loaded in your web route.
You could name the route and use BLADE to set a Javascript variable to that route.
For example:
Route::get('/', 'MyAmazingController#function')->name('my.awesome.route');
Then in your Javascript you can do something like:
url: '{{ route('my.awesome.route') }}';
If you have the javascript in a seperate file, you could create a constant in your view with routes in it.
val ROUTES = {
AJAX: '{{ route('my.awesome.route') }}'
}
I try to post data to laravel controller using ajax, but still get response null. My achievement is to post form data and return error message or success message.
I'm newbie in ajax and laravel framework please help me to solve the problem.
Here is the meta tag header:
<meta name="_token" content="{{ csrf_token() }}">
Here is the html form :
{{ Form::open(['id'=>'testimonial_form','url'=>URL::action("processing-give-testimonial"),'method'=>'POST']) }}
{{ Form::hidden('_method', 'PUT') }}
<div class="row marginbot-20">
<div class="col-md-6 xs-marginbot-20">
{{ Form::text('name',null, ['class'=>'form-control input-lg','placeholder'=>'Enter Name','id'=>'name']) }}
</div>
<div class="col-md-6">
{{ Form::email('email',null, ['class'=>'form-control input-lg','id'=>'email','placeholder'=>'Enter email','id'=>'email']) }}
</div>
</div>
<div class="row">
<div class="col-md-12">
<div class="form-group">
<select name="subject" id="subject" class="form-control" require="required">
<option value="ask">Ask Question / Information</option>
<option value="testimonial">Give Feedback / Testimonial</option>
</select>
</div>
<div class="form-group">
{{ Form::textarea('message',null,['id'=>'message','class'=>'form-control','rows'=>'4','cols'=>'25','placeholder'=>'message','id'=>'message']) }}
</div>
<!-- {{ Form::submit('Send Message',['id'=>'btnContactUs','class'=>'btn btn-skin btn-lg btn-block']) }} -->
{{ Form::button('Submit', ['class'=>'btn btn-skin btn-lg btn-block','id'=>'click']) }}
</div>
</div>
{{ Form::close() }}
Here is the ajax code :
$(function() {
$.ajaxSetup({
headers: {
'X-XSRF-Token': $('meta[name="_token"]').attr('content')
}
});
});
$(document).ready(function() {
$('#click').click(function() {
var formData = {
name : $('#name').val(),
email : $('#email').val(),
subject : $('#subject').val(),
message : $('#message').val(),
};
$.ajax({
type : "POST",
url : "{{ URL::action('processing-give-testimonial') }}",
data : formData,
beforeSend: function () {
alert('sure?');
},
success: function(data) {
console.log(data);
},
error: function() {
console.log('error');
}
});
});
});
Here is the controller :
public function create()
{
$inputs = array(
'name' =>Input::get('name'),
'email' =>Input::get('email'),
'subject' =>Input::get('subject'),
'message' =>Input::get('message')
);
//return "we reached here";
return Response::json("success");
/*if(Request::ajax()) {
return Response::json('success', 200);
} else {
return Response::json('failed', 400);
}*/
/* if(Request::ajax()) {
$data = Input::get('email');
//print_r($data);die;
if ($data != '') return Response::json('success',200);
else return Response::json('failed',400);
}*/
/*
$input = Input::get('name');
//$input = Input::get('_token');
if ($input == '') {
return Response::json('failed',400);
}
else {
return Response::json('success',200);
}*/
//if(!empty($input)) return Response::json(['data'=>'success']);
//else return Response::json('data',$input);
}
Here is the my route :
Route::post('give-testimonial',['uses'=>'TestimonialController#store','as'=>'processing-give-testimonial']);
Here is the filter.php :
Route::filter('csrf', function() {
$token = Request::ajax() ? Request::header('X-XSRF-Token') : Input::get('_token');
if (Session::token() != $token) {
throw new Illuminate\Session\TokenMismatchException;
} });
I'm guessing your routing is wrong. Try changing this route:
Route::post('give-testimonial',['uses'=>'TestimonialController#store','as'=>'processing-give-testimonial']);
to this:
Route::post('give-testimonial',['uses'=>'TestimonialController#create','as'=>'processing-give-testimonial']);