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,
})
})
Related
How to set value to customerNumber(field from Marketing table) from database when I select an option from Request Number drop down list?
<div class="col-sm-2">
<label class="label" for="request_id">Request Number:</label>
<select class="form-control option" id="request_id">
<option >0 - Request Number</option>
#foreach ($customer_requests as $customer_request)
<option value={{$customer_request->id}}>{{$customer_request->id}} -{{$customer_request->requestNumber}} </option>
#endforeach
</select>
</div>
<div class="col-sm-2">
<label class="label" for="customerNumber" >Customer Number:</label>
<input type="text" class="form-control text" id="customerNumber" name="customerNumber">
</div>
I am a learner of laravel and I want to know should jQuery be used or not? And how?
<script>
$("#request_id").on({
click: function() {
}, keypress: function() {
$( this ).addClass( "inside" );
var val = $(this).val();
var data = Marketing::find(val);
$("#customerNumber").attr("value", data[customerNumber] );
}
});
</script>
for the jquery you can try like this one:
$('#request_id').change(function() {
var req_id= $(this).val();
$.ajax({
url:'{{url('/get/ref')}}/'+req_id,
method:'GET',
contentType: false,
processData: false,
success:function(result){
$("#customerNumber").val(result);
}
});
});
then, create a new controller to return customerNumber. something like:
public function customerNumber($req_id = 0){
$data = Marketing::find($req_id);
return $data->customerNumber;
}
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 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);
});
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 have some problems with receiving data when using an ajax call to EDIT my data. I'm trying to get data that the user has filled in but every time my data is empty or 'null'. Do i need to pass data in ajax call? Or are there other ways in laravel to get the data?
My code at the moment as we speak:
showuser.blade.php
<div class="comments">
#if(count($user->cars))
<h1>Auto in reparatie</h1>
<hr>
#foreach($user->cars as $car)
<!-- Form to show each car and edit / delete the cars -->
<!--<form action="{{ action('CarController#edit', [$user->id, $car->id]) }}" method="POST">-->
<form>
<div class="form-group">
<label for="brand">Merk:</label><br>
<select name="brand">
#foreach($brands as $brand)
<option value="{{$brand->id}}"{{ $brand->id == $car->brand_id ? ' selected="selected"' : '' }}>{{$brand->brandname}}</option>
#endforeach
</select>
</div>
<div class="form-group">
<label for="year">Bouwjaar:</label><br>
<input type="text" value="{{$car->year}}" name="year">
</div>
<div class="form-group">
<label for="licentsplate">Kenteken:</label><br>
<input type="text" value="{{$car->licensplate}}" name="licenseplate">
</div>
<div style="float: left; width: 80px">
<input type="submit" class="btn btn-primary" value="Edit" id="{{$car->id}}" name="editcar" />
</div>
</form>
<form>
<div class="form-group">
<button class="btn btn-primary" name="deletecar" id="{{$car->id}}">Delete</button>
</div>
</form>
#endforeach
#endif
</div>
Script
<script type="text/javascript">
$( document ).ready(function() {
$('[name="editcar"]').click(function (e){
e.preventDefault();
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
})
});
});
</script>
Routes
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
CarController.php
// Function to edit a car by ID
public function edit($userId, $carId)
{
$car = Car::where('id', $carId)->where('user_id', $userId)->first();
$car->brand_id = request('brand');
dd(request('year'));
$car->year = request('year');
$car->licensplate = ('licenseplate');
$car->save();
}
If I dump and die request('brand'), request('year'), request('licenseplate') i get 'null'.
EDIT:
If I dd $car in my controller, i get the car that i need. Means that there is no problemen finding the right car.
Thx for reading!
You aren't posting any data in the AJAX request. Pass the form values through in an object.
var form = $(this).find('form');
var licenseval = form.find('input[name=licenseplate]').val();
var yearval = form.find('input[name=year]').val();
var brandval = form.find('select[name=brand]').find(":selected").val();
$.ajax({
type: "POST",
data: {licenseplate: licenseval, year: yearval, brand: brandval}
url: '/users/{{$user->id}}/cars/'+this.id,
success:function(data){
if(!data.error){
location.reload(true);
}
}
});
Change following lines:
public function edit($userId, $carId)
to
public function edit(Request $request, $userId, $carId)
and use
use Illuminate\Http\Request;
after that you can get $userId, $carId to use inside the controller function.
As per your ajax call you are only calling the route
Route::post('/users/{userId}/cars/{carId}', 'CarController#edit');
but you are not passing any other value. Your application is working as expected.
$.ajax({
type: "POST",
url: '/users/{{$user->id}}/cars/'+this.id,
//data: dataObject, ----->Missing Data which you want to pass (brand, year, licenceplate)
success:function(data){
//...
}
})
You are iterating through multiple $cars you need to get current car's data and pass to ajax call.