Laravel - How to extract value from JSON into the textbox - json

In my Laravel-5.8, I passed data from controller to view using JSON.
public function findScore(Request $request)
{
$userCompany = Auth::user()->company_id;
$child = DB::table('appraisal_goal_types')->where('company_id', $userCompany)->where('id',$request->id)->first();
if(empty($child))
{
abort(404);
}
$maxscore2 = 1;
$maxscore = DB::table('appraisal_goal_types')->select('max_score')->find($child->parent_id);
return response()->json([
'maxscore' => $maxscore,
'maxscore2' => $maxscore2
]);
}
Route
Route::get('get/findScore','Appraisal\AppraisalGoalsController#findScore')
->name('get.scores.all');
View
<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" value="max_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(data.maxscore);
console.log(data.maxscore2);
$('#max_score').val(data.maxscore);
},
error:function(){
}
});
});
});
</script>
When I click on the dropdown on change, I got these:
Console:
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 the 75 in the textbox.
How do I get this resolved?
Thank you.

You're seeing this result because maxscore is an object. You can either reference maxscore.max_score from JavaScript when adding to the element, or you can alternatively look at your eloquent code. You can likely replace the ->find() with calls to ->where() and ->first() as you did with $child

You can access the inner elements using something like this, or at least have an idea , and then you can print the elemet you need from the array...
var selectedValue = max_score.options[max_score.selectedIndex].innerHTML;
var arreglo = selectedValue.split(' ');
var arreglo1 = arreglo[0];

Related

passing two arrays in foreach

passing ajax posting values in php laravel controller only one selected dropdown options array values are inserted so required two arrays of two selected drop list values to be inserted
get array of values
'$.ajax({
dataType: 'json',
url: "/getCity/"+id,
type: "GET",
success: function (data) {
console.log(data);
$('select[name="GLNO[]"]').empty();
$.each(data, function(key,data){
$('select[name="GLNO[]"]').append('<option value="'+ data.GLNO +'">'+ data.GLNO +'</option>');
});
$('select[name="NAME[]"]').empty();
$.each(data, function(key,data){
$('select[name="NAME[]"]').append('<option value="'+ data.NAME +'">'+ data.NAME +'</option>');
});
``
post array of values
$('#ProductForm').submit(function(e) {
e.preventDefault();
var formData = new FormData(this);
$.ajax({
type: 'POST',
url: "{{ url('store-product') }}",
data: formData,
cache: false,
contentType: false,
processData: false,
success: (data) => {
$("#product-modal").modal('hide');
var oTable = $('#products').dataTable();
oTable.fnDraw(false);
$("#btn-save").html('Submit');
$("#btn-save").attr("disabled", false);
},
error: function(data) {
console.log(data);
}
});
});
form of multiple selected dropdown
<div class="form-group">
<label for="name" class="col-sm-2 control-label">GLNO</label>
<div class="col-sm-12">
<select name="GLNO[]" multiple id="glno" class="form-control" >
<option value=""></option>
</select>
</div>
</div>
<div class="form-group">
<label for="name" class="col-sm-2 control-label">GLNO</label>
<div class="col-sm-12">
<select name="NAME[]" multiple id="name" class="form-control" >
<option value=""></option>
</select>
</div>
</div>
controller of store
public function store(Request $request)
{
$productId = $request->id;
$request->validate([
'fmcode',
'fmcodes',
'area',
'naoffm','glno','frmdate',
'todate'
]);
$input = $request->all();
$products=$request->GLNO;
foreach ((array)$products as $product1) {
$product = Product::updateOrCreate(
[
'id'=> $productId ,
'fmcode' => $request->FMCODE,
'fmcodes' => $request->FMCODES,
'area' => $request->AREA,
'naoffm' => $request->NAOFFM,
'frmdate' => $request->frmdate,
'todate' => $request->todate,
'glno'=>$product1
]
);
}
return Response()->json($product);
}'
inserting two array multiple selected dropdown list values its showing error of inserting values so how we can pass values in for each loop for two request of values

ERROR: Trying to get property id error in Laravel (non object)

can you please describe whats wrong with my code below. Their is an error when I click Update button and getting id of update Request. What I want to do is to update category name and tag with a post (post_tag i.e belongstoMany)
And it says "Trying to get property of non-object.
//class Post extends Model
public function category()
{
return $this->belongsTo('App\Category');
}
public function tags()
{
return $this->belongsToMany('App\Tag');
}
// class Tag extends Model
public function posts()
{
return $this->belongsToMany('App\Post');
}
// class Category extends Model
protected $table = 'categories';
public function posts()
{
return $this->hasMany('App\Post');
}
// PostController
public function edit($id)
{
// find the post in the database and save as a var
$post = Post::find($id);
$categories = Category::with('posts')->get();
$cats = array();
foreach ($categories as $category) {
$cats[$category->id] = $category->name;
}
$tags = Tag::with('posts')->get();
$tags2 = array();
foreach ($tags as $tag) {
$tags2[$tag->id] = $tag->name;
}
// return the view and pass in the var we previously created
return view('backend.pages.posts.edit')->withPost($post)->withCategories($cats)->withTags($tags2);
}
/**
* Update the specified resource in storage.
*
* #param \Illuminate\Http\Request $request
* #param int $id
* #return \Illuminate\Http\Response
*/
public function update(Request $request, $id)
{
// Validate the data
$post = Post::find($id);
if ($request->input('slug') == $post->slug) {
$this->validate($request, array(
'title' => 'required|max:255',
'category_id' => 'required|integer',
'body' => 'required'
));
} else {
$this->validate($request, array(
'title' => 'required|max:255',
'slug' => 'required|alpha_dash|min:5|max:255|unique:posts,slug',
'category_id' => 'required|integer',
'body' => 'required'
));
}
// Save the data to the database
$post = Post::find($id)->first();
$post->title = $request->input('title');
$post->slug = $request->input('slug');
$post->category_id = $request->input('category_id');
$post->body = $request->input('body');
if (isset($request->tags)) {
$post->tags()->sync($request->tags);
} else {
$post->tags()->sync(array());
}
$post->save();
notify()->success("The blog post was successfully updated!", 'Success');
return redirect()->route('app.posts.show', $post->id);
// return back();
}
//edit.blade.php file
// An error appears in select option finding an id which is a non-object
// A 2 line code below which is inside of form POST METHOD {{ route('app.posts.update', $post->id) }} //
<select class="form-control" name="category_id" class="form-control #error('category_id') is-invalid #enderror" required>
#foreach($categories as $key=>$category)
<option value="{{ $category>id }}" #isset($post) {{ $post->category->id == $category->id ? 'selected' : '' }} #endisset>{{ $category->name}}</option>
#endforeach
// Same error below tag name cannot get property
<select class="form-control select2-multi" id="tags" name="tags[]" multiple>
#foreach($tags as $key=>$tag)
<option value="{{ $tag }}" {{ old('tags[]', $post->tag)->contains($tag) ? 'selected' : '' }}>{{ $tag->name }}</option>
#endforeach
</select>
//End form
I got it. the $categories variable the you pass to the view is an array, with keys are category ids and values are category names. In your view, inside the loop, that $category variable is a string, but you try to access that as an object ($category->id) and get the error.
SOLUTION 1:
You can update your code like this:
<select class="form-control" name="category_id" class="form-control #error('category_id') is-invalid #enderror" required>
#foreach($categories as $categoryId => $categoryName)
<option value="{{ $categoryId }}" #isset($post) {{ $post->category->id == $categoryId ? 'selected' : '' }} #endisset>{{$categoryName}}</option>
#endforeach
<select class="form-control select2-multi" id="tags" name="tags[]" multiple>
#foreach($tags as $tagId => $tagName)
<option value="{{ $tagId }}" {{ old('tags[]', $post->tags)->contains($tagId) ? 'selected' : '' }}>{{ $tagName }}</option>
#endforeach
</select>
SOLUTION 2:
I see that in the controller action, you transform you categories and tags to arrays, which is not necessary. Just get those from the database and pass to the view.
public function edit($id)
{
// find the post in the database and save as a var
$post = Post::find($id);
$categories = Category::with('posts')->get();
$tags = Tag::with('posts')->get();
return view('backend.pages.posts.edit', [
'post' => $post,
'categories' => $categories,
'tags' => $tags,
]);
// Or you can even write: return view('backend.pages.posts.edit', compact('post', 'categories', 'tags'));
}
Then in your view:
<select class="form-control" name="category_id" class="form-control #error('category_id') is-invalid #enderror" required>
#foreach($categories as $category)
<option value="{{ $category->id }}" #isset($post) {{ $post->category->id == $category->id ? 'selected' : '' }} #endisset>{{$category->name}}</option>
#endforeach
<select class="form-control select2-multi" id="tags" name="tags[]" multiple>
#foreach($tags as $tag)
<option value="{{ $tag->id }}" {{ old('tags[]', $post->tags)->contains($tag->id) ? 'selected' : '' }}>{{ $tag->name }}</option>
#endforeach
</select>

Laravel- Auto fill input after selecting value from dropdown

how to do the auto fill after select the dropdown list. I'm not really good in js or ajax.
When user select doc_no then both rev_no and title field must be filled up. Thanks!
View
<div class="form-group">
{!! Form::label('text', 'Doc No', ['class' => 'col-lg-3 control-label']) !!}
<div class="col-lg-10">
<select name="docNo" id="docNo" class="form-control" style="width:250px">
#foreach ($soplists as $soplist)
<option value="{{ $soplist->id }}">{{ $soplist->doc_no }}</option>
#endforeach
</select>
</div>
</div>
<input type="hidden" name="carType" value="Internal Audit" class="form-control">
<div class="form-group">
{!! Form::label('text', "Rev No", ['class' => 'col-lg-5 control-label']) !!}
<div class="col-lg-5">
<input type="text" class="form-control" id="rev" />
</div>
</div>
<div class="form-group">
{!! Form::label('text', "Title", ['class' => 'col-lg-5 control-label']) !!}
<div class="col-lg-10">
<input type="text" class="form-control" id="title" />
</div>
<script>
$('#docNo').change(function() {
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response) {
if (response != null) {
$('#rev').val(response.rev_no);
$('#title').val(response.title);
}
}
});
});
</script>
Controller
---php
public function getDetails($id = 0)
{
$data = sopList::where('doc_no', $id)->first();
echo json_encode($data);
exit;
}
Route
'Route::get('get/details/{id}', 'internalAuditController#getDetails')->name('getDetails');'
Database sop_list table image link
https://ibb.co/SwkJhLc
Dropdown and input image
https://ibb.co/0VN3Z2y
Network tab
https://ibb.co/56w5BLD
Add a route in web.php file:
Route::get('get/details/{id}', 'YourController#getDetails')->name('getDetails');
Controller Function:
public function getDetails($id = 0)
{
$data = sopList::where('doc_no',$id)->first();
return response()->json($data);
}
And in view the script:
$('#docNo').change(function(){
var id = $(this).val();
var url = '{{ route("getDetails", ":id") }}';
url = url.replace(':id', id);
$.ajax({
url: url,
type: 'get',
dataType: 'json',
success: function(response){
if(response != null){
$('#rev').val(response.rev_no);
$('#title').val(response.title);
}
}
});
});
Make sure to add the id rev and title to the rev and title input fields respectively.
you have to make a rout that returns what you need
for example
/**
* #return \Illuminate\Http\JsonResponse
*/
public function getCategories()
{
$category = Category::where('_id', request()->get('_id'))
->select(['name', '_id'])->first();
return response()->json($category);
}
then call it on change of your select box with ajax and show it every where you want
like this example:
$("#docNo").change(function () {
$.ajax({
url: "{{ route('getCategories') }}",
type: 'POST',
data: {
_token: "{{ csrf_token() }}",
_id: $(this).val()
},
success: function (data) {
var newOption = '';
$.each(data, function (k, category) {
newOption += '<option value="' + category.id + '">' + category.name + '</option>';
});
$('#parent').append(newOption);
},
error: function (error) {
console.log(error);
}
});
});
you can add onChange method on your docNo and then call do ajax call to get the rev_no and title and update the content via document.getElementById()

AngularJS function doesn't run

I have the following angular factory and controller.
var app = angular.module("carForm", []);
app.factory("dataService", ['$http', function getData($http) {
function getCars(){
return $http({
method: 'GET',
url: '/data.json'
}).then(function (response){
console.log(response.data);
return response.data
},function (error){
console.log("product error");
})
};
return { getCars : getCars }
}]);
app.controller("dataSort", ['dataService', '$scope', function(dataService, $scope) {
dataService.getCars().then(function(response){
cars = response;
$scope.make = [];
for (key in cars){
item = cars[key];
console.log(item);
$scope.make.push(item);
}
$scope.model = [];
for (key in cars[$scope.selectMake]){
item = cars[item][key_2]
$scope.model.push(item)
}
})
search = function(cars){
cars[$scope.selectMake][$scope.selectModel][$scope.selectType]
}
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div class="col-12" ng-contoller="dataSort">
<div class="row" style="text-align: center;">
<div class="form-group col-6">
<label for="inputState">Make</label>
<select id="inputState" class="form-control">
<option ng-model="selectMake" selected>Select make</option>
<option ng-repeat="item in make">{{ item }}</option>
</select>
</div>
<div class="form-group col-6">
<label for="inputState">Model</label>
<select id="inputState" class="form-control">
<option ng-model="selectModel" selected>Select model</option>
<option ng-repeat="item in model">{{ model }}</option>
</select>
</div>
<div class="form-group col-3">
<label for="inputState">Type</label>
<select id="inputState" class="form-control">
<option ng-model="selectType"selected>Select make type</option>
<option ng-repeat="item in type">{{ model }}</option>
</select>
</div>
</div>
</div>
I don't believe either factory or controller are running. Nothing is logged in console, neither the data or the error message. Angular is properly linked to my form as there is no {{ }} also the ng app is declared at the top of the html in the body tag using ng-app="carForm". The JS page is correctly linked to the html as when I console.log outside the angular function it prints. Angular is loaded before my JS script in the head tag, I cant figure out what I'm doing wrong.
Your factory is uncorrected, because you didn't pass your function in return
Right way to make a factory
app.factory("dataService", ['$http', function($http) {
var x = {};
return x;
}]);
But even you change the code it's not work on your controller because
you want to return response.data in $http as promise and this not happens, in
the case you need $q as injection in your service.
var app = angular.module("carForm", []);
app.factory("dataService", ['$http', '$q', function ($http, $q) {
var factory = {}
factory.sample = function() {
console.log("in factory!");
return [1,2,3]
}
factory.getCars = function() {
var deferred = $q.defer();
$http.get("api").then(function(response){
deferred.resolve(response.data);
})
return deferred.promise;
}
return factory;
}]);
app.controller("dataSort", ['dataService', '$scope', function(dataService, $scope) {
$scope.items = dataService.sample();
//uncomment when your api was ready
//dataService.getCars().then(function(response){
// console.log(response);
//})
}]);
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.7.5/angular.min.js"></script>
<div ng-app="carForm" ng-controller="dataSort">
<ul>
<li ng-repeat="item in items">{{item}}</li>
<ul>
</div>
Your factory is not correctly implemented Please change it like this.
app.factory("dataService", ['$http', function($http) {
function getCars(){
return $http({
method: 'GET',
url: '/data.json'
}).then(function (response){
console.log(response.data);
return response.data
},function (error){
console.log("product error");
})
};
return { getCars : getCars }
}]);

How to use ng if condition in a single div for multiple condition

I have a select dropdown,and divs coming from loop.Here when I change the drop down option to city,my div id should change to one,two three which comes from details column from json.Again when I change the drop down option to state,my div id should change to title1,title2 title3 which comes from title column from json.Here it is working fine but I am creating new divs for each condition,can it possible to make in a single div with multiple condition.Here is the code below.
HTML
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-if="id=='city'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.details}}" >hello</div>
</div>
<div ng-if="id=='state'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.title}}" >hello</div>
</div>
<div ng-if="id=='country'">
<div ng-repeat="emp in groups" ng-attr-id="{{emp.name}}" >hello</div>
</div>
script
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [
{
title: 'title1',
name:'name1',
details:'one'
},
{
title: 'title2',
name:'name2',
details:'two'
},
{
title: 'title3',
name:'name2',
details:'three'
}
]
$scope.update = function() {
if($scope.x == 'city'){
$scope.id='city';
}
if($scope.x == 'state'){
$scope.id='state';
}
if($scope.x == 'country'){
$scope.id='country';
}
}
});
To achieve the desired result, try to:
create an attr for each value - city, state and country, like so:
if($scope.x == 'city'){
$scope.id='city';
$scope.attr = 'details';
}
Use {{emp[attr]}} to display values based on the dropdown selection:
var app = angular.module("myApp", []);
app.controller("myCtrl", function($scope) {
$scope.groups = [{
title: 'title1',
name: 'name1',
details: 'one'
},
{
title: 'title2',
name: 'name2',
details: 'two'
},
{
title: 'title3',
name: 'name2',
details: 'three'
}
]
$scope.update = function() {
if ($scope.x == 'city') {
$scope.id = 'city';
$scope.attr = 'details';
}
if ($scope.x == 'state') {
$scope.id = 'state';
$scope.attr = 'title';
}
if ($scope.x == 'country') {
$scope.id = 'country';
$scope.attr = 'name';
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.6.9/angular.min.js"></script>
<body>
<div ng-app="myApp" ng-controller="myCtrl">
<select class="change" ng-model="x" ng-change="update()">
<option value="city">Cities</option>
<option value="state">States</option>
<option value="country">Countries</option>
</select>
<div ng-repeat="emp in groups" ng-attr-id="{{emp[attr]}}">{{emp[attr]}}</div>
</div>
</div>
codepen - https://codepen.io/nagasai/pen/wRQWRM
To this in a singal element you can use a nested ternary operator. For your case it will look like that:
<div ng-repeat="emp in groups" ng-attr-id="{{id=='city' ? emp.details : id=='state' ? emp.title : emp.name}}" >hello</div>
I didn't implement this on angular 1 but it works on angular 2. Angular built in directive (ngif, ngfor ngclass etc) works almost same for both versions.