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(){
}
});
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,
})
})
I am creating a Ticket Reservation System and I want to check data availability from the Database. As usual, I used HTML form and when someone tries to insert data which is already in the database , I want to show them a message as "Data Already Have". And If data is unique , I want to insert into the database. But , when I click Submit button, nothing happens. ( Seat Number = Items )
In the console of the browser shows these errors -
POST http://localhost/FinalProject/public/seatprocess 500 (Internal
Server Error) XHR failed loading: POST
"http://localhost/FinalProject/public/seatprocess"
In Network tab -> Response shows like this -
{
"message": "Object of class Illuminate\\Database\\Query\\Builder could not be converted to string",
"exception": "ErrorException",
"file": "D:\\wamp64\\www\\FinalProject\\app\\Http\\Controllers\\SeatsController.php",
"line": 42,
"trace": [
{
"file": "D:\\wamp64\\www\\FinalProject\\app\\Http\\Controllers\\SeatsController.php",
"line": 42,
"function": "handleError",
"class": "Illuminate\\Foundation\\Bootstrap\\HandleExceptions",
"type": "->"
},
And this is continuesly going. May be my seatprocess function is wrong. But , I have no idea how to Fix it.
Form and Seat Structure Image
How can I Fix this ??
Here is my Seats.blade.php
<form class="form-horizontal" id="form1" method="POST" action="{{ route('seatsinsert') }}" enctype="multipart/form-data">
{{ csrf_field() }}
<div class="dt"> <br>
<h4> <span id="success_message" class="text-success"></span> </h4>
<div class="form-group row">
<label for="example-date-input" class="col-2 col-form-label">Select Date :</label>
<div class="col-10">
<input class="form-control" type="date" name="date" placeholder="mm-dd-yyyy" id="example-date-input">
</div>
</div>
<div class="form-group">
<label for="exampleSelect1">Select Time :</label>
<select name="st" class="form-control" id="exampleSelect1">
<option>10.30 am</option>
</select>
</div>
</div>
<h2 style="font-size:1.2em;font-family: Times New Roman;"> Choose seats by clicking below seats :</h2>
<div id="holder">
<ul id="place">
</ul>
</div>
<div style="width:600px;text-align:center;overflow:auto"> <br>
<input type="submit" class="btn btn-primary" id="btnShowNew" value="Continue"> <br><br>
<span id="availability"></span>
<script type="text/javascript">
$(function () {
$('#btnShowNew').click(function (e) {
e.preventDefault();
var items = [];
$.each($('#place li.' + settings.selectingSeatCss + ' a'), function (index, value) {
items.push($(this).attr('title'));
});
console.log(items);
// $(location).attr('href', 'Seats');
$.ajax({
url:'{{ route('seatprocess') }}',
type:"POST",
data:{
_token: "{{ csrf_token() }}",
items: JSON.stringify(items),
date: $('input[name=date]').val(),
st: $('select[name=st]').val()},
success:function(data)
{
if(data !== '0')
{
$('#availability').html('<span class="text-danger">Seats not available</span>');
$('#btnShowNew').attr("disabled", true);
}
else
{
//$('#availability').html('<span class="text-success">Seats Available</span>');
$.ajax({
type: "post",
url: "{{ route('seatsinsert') }}",
data: {
_token: "{{ csrf_token() }}",
items: JSON.stringify(items),
date: $('input[name=date]').val(),
st: $('select[name=st]').val()},
success: function(data){
$("form").trigger("reset");
$('#success_message').fadeIn().html("Text");
}
});
$('#btnShowNew').attr("disabled", false);
}
}
});
}); //btnShowNew
}); //Final
</script>
</form>
Here is my SeatsController.php
public function seatsinsert(Request $request)
{
$date = $request->input('date');
$st = $request->input('st');
$items = $request->input('items');
$items = str_replace(['[', ']', '"'], '', $items);
$user = new Seats();
$user->date = $date;
$user->st = $st;
$user->item = $items;
$user->save();
}
public function seatprocess(Request $request)
{
//dd($request->all());
$items = $request->input('items');
$results = DB::table('seats')->where('item',$items);
echo $results;
}
}
Here are my Routes.
Route::post('seatsinsert',[
'uses'=> 'SeatsController#seatsinsert',
'as' => 'seatsinsert'
]);
Route::post('seatprocess',[
'uses'=> 'SeatsController#seatprocess',
'as' => 'seatprocess'
]);
You need to retrieve data in your response function with get like this before echo the $result variable.
This is the reason behind error in your console.
you have to change the line like this:
$results = DB::table('seats')->where('item',$items)->get();
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 have in my form two dependant dropdowns based on the first select option.
When i am attempting to store to the DB i get the following problem....
Integrity constraint violation: 1048 Column 'service_id' cannot be null
Can someone help me identify where my problem is and how to fix, i think it is related to my store method because the dependant dropwdowns
Here is how i pass to the view:
$services = \DB::table('services')->lists("name", "id");
return view ('reservations', compact('services'));
Here is my form in view:
{!! Form::open(array("url"=>"bookings", "class"=>"form-horizontal")) !!}
<select name="service" class="form-control" style="width:350px">
<option value="">--- Select Service ---</option>
#foreach ($services as $key => $value)
<option value="{{ $key }}">{{ $value }}</option>
#endforeach
</select>
<br />
<label for="price">This cost for this service is:</label><br />
<select name="price">
<option id="price"></option>
</select><br />
<label for="time">This duration for this service is:</label><br />
<select name="time">
<option id="time"></option>
</select>
<br />
<br />
{!! Form::label("booking_date", "Enter Date", array("class"=>"col-md-2")) !!}
{!! Form::text("booking_date","",array("placeholder"=>"Enter Date", "class="=>"form-control")) !!}
<br />
<br />
{!! Form::label("booking_time", "Enter Time", array("class"=>"col-md-2")) !!}
{!! Form::text("booking_time","",array("placeholder"=>"Enter Time", "class="=>"form-control")) !!}
<br />
<br />
{!! Form::submit('Book', array("class"=>"btn btn-primary","id"=>"btn")) !!}
{!! Form::close() !!}
Here is the JS for dependant dropdowns:
$(document).ready(function() {
$('select[name="service"]').on('change', function() {
var serviceID = $(this).val();
if(serviceID) {
$.ajax({
url: '/myform/ajax/'+serviceID,
type: "GET",
dataType: "json",
success:function(data) {
$('option[id="price"]').empty();
$.each(data, function(key, value) {
$('option[id="price"]').append('<p value="'+ key +'">£'+ value +'</p>');
});
}
});
}else{
$('option[id="price"]').empty();
}
});
});
$(document).ready(function() {
$('select[name="service"]').on('change', function() {
var serviceID = $(this).val();
if(serviceID) {
$.ajax({
url: '/serviceTime/ajax/'+serviceID,
type: "GET",
dataType: "json",
success:function(data) {
$('option[id="time"]').empty();
$.each(data, function(key, value) {
$('option[id="time"]').append('<p value="'+ key +'">'+ value +' minutes</p>');
});
}
});
}else{
$('option[id="time"]').empty();
}
});
});
Here is my controller store method:
public function store(Request $request)
{
//
$data = \Input::only("booking_date", "booking_time");
$bookings = new Booking($data);
$bookings->user_id = auth()->user()->id;
$bookings->service_id = $request->get('serviceID');
$bookings->service_price = $request->get('price');
$bookings->booking_date = $request->get('booking_date');
$bookings->booking_time = $request->get('booking_time');
$bookings->save();
return redirect('/');
}
in the model:
protected $fillable = ['service_price', 'service_time','booking_date', 'booking_time'];
Super simple, there is a field in your database called service_id that must be filled and have a value.
In your php, you expect form field called serviceID, but in your html you call it service.
<select name="service" class="form-control" style="width:350px">
Different names, so change one of them to the other.
Your selection form field name 'service' but you try to get value using $request->get('serviceID') that's why your got error.
Replace your store method.
public function store(Request $request,int $service)
{
//
$data = \Input::only("booking_date", "booking_time");
$bookings = new Booking($data);
$bookings->user_id = auth()->user()->id;
$bookings->service_id = $request->get('service');
$bookings->service_price = $request->get('price');
$bookings->booking_date = $request->get('booking_date');
$bookings->booking_time = $request->get('booking_time');
$bookings->save();
return redirect('/');
}
Or replace 4th line of your store method with
$bookings->service_id = $request->get('service');
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']);