I have a select element and based on the the selection, data is to be retrieved based on the id selected.
blade template
<div id="pers_obj" class="form-group form-duration-div">
{{Form::label("personal_objective", "Personal Objective/KPA")}}
<select name="personal_objective" id="personal_objective" v-model="personal_objective">
<option value="0" class="form-control">--Select Objective--</option>
#foreach($personal_objectives as $personal_objective)
<option value="{{ $personal_objective->id }}" class="form-control">{{ $personal_objective->name}}</option>
#endforeach
</select>
<div v-cloak>#{{personal_objective}}</div>
</div>`
measure.js
var pers_objective = new Vue({
el: '#pers_obj',
data:{
personal_objective: null
},
});
How can I:
retrieve data from database using vuejs
display data from the database using vue js
Looks like you are mixing a bit the PHP and JavaScript code trying some luck. The best way is creating a service response to get the personal objectives like an API.
So lets supose that you create a controller, called at /personal-objectives for example, that returns an array of objects with the structure of { id: number, name: string }
Then your code for the HTML would look like:
<div id="pers_obj" class="form-group form-duration-div">
<select name="personal_objective" v-model="personal_objective">
<option value="0" class="form-control">--Select Objective--</option>
<option v-for="po in pos" value="#{{ po.id }}" class="form-control">#{{ po.name }}</option>
</select>
</div>
And your JavaScript (assuming you are ussing vue-resource library for ajax calls) like:
var pers_objective = new Vue({
el: '#pers_obj',
data: function() {
return {
personal_objective: null,
pos: [];
};
}
created: function() {
this.loadPersonalObjectives();
}
methods: {
loadPersonalObjectives: function() {
this.$http.get('personal-objectives').then((response) => {
this.pos = response.data.pos;
}, (response) => {
console.log(response);
});
}
}
});
The above code will make an ajax GET call when the component is created to /personal-objectives which will return a JSON (don't forget to return the array encoded this way and set the proper header) array of bjects that on error will be displayed in console, and on succed the array will be assigned to the pos javascript variable and updated in the HTML creating the corresponding options reactively!
You may need to update the URL adding the root / in case you are not configuring the vue-resource with the root option (Vue.http.options.root)
Related
I am passing an object from my controller to my blade.php.file. From there I use object notation to get the variables from my object which leaves me with an array. I then am trying to pass that array of data from my blade.php file to my vue component. I want to pass the entire array not just one index of it. As of right now when I try to pass the array I get the error htmlspecialchars() expects parameter 1 to be string, array given which makes sense because I am passing an array (which is what I want). How do I successfully pass an array of data from laravel blade to VUE?
blade.php file
<div id="app">
<draggable
draggable-table="{{ $table->vars }}">
</draggable>
</div>
VUE component
<template>
</template>
<script>
export default {
props: ['draggableTable'],
};
</script>
EDIT:
As suggested to me I added a : and json_encode in my blade fole table like so:
:draggable-table="{{json_encode($table->vars)}}">
But when I check my VUE console my component no longer shows and only root is shown with none of the array data passed in. (See photo)
2ND EDIT:
I am trying to do this via axios now. I added this to my component within the <script> tags
data(){
return{
table: this.draggableTable
}
},
methods: {
getData(){
axios.get(this.endpoint, {
table: this.table,
}).then(res => {
console.log(res);
}).catch(err => {
console.log(err);
});
}
},
computed: {
endpoint(){
return window.location.protocol + "//" + window.location.host + '/users';
}
}
app.js
const app = new Vue({
el: '#app'
});
So now how to I pass the data from blade to VUE?
Thank you.
you have to add : in prop, live below code.
<div id="app">
<draggable
:draggable-table="{{ json_encode($table->vars) }}">
</draggable>
</div>
You can just send it as a JSON object and then parse it either in Vue or when accepting it as a prop.
<div id="app">
<draggable
:draggable-table=JSON.parse({{ json_encode($table) }})>
</draggable>
</div>
Why would you need to pass data from Blade to Vue if you are using an API call in Vue? Data is already available to you.
6, I'm using a dropdown to read a column from a database table. All I want is to get the selected value on that dropdown and use it to create a new query that will be populated in a new drop-down.
After reading and see several examples I see people using ajax and other people using laravel HTTP request like $request->get() so i don't know which way to take since I'm not familiar with any of those and even when trying several times can't get it to work.
Can anyone give me an insight into the best/efficient way to do it? Is it possible to do it only using php or some feature in laravel that I'm missing?
Here is my controller:
public function selectsector() //this is the dropdown #1 that works fine
{
$sectors = DB::table('Sectors')->whereBetween('SectorID', [1, 10])->value('SectorID');
return view('besttradesview', ['sectors10' => $sectors]);
}
public function selectsubsector() //dropdown #2 not working
{
$subsectors = DB::table('Sectors')->where('parentid', $sectors)->get();
//this line is not working it does not recognize $sector variable
return view('besttradesview', ['subsectors42' => $subsectors]);
}
View with dropdow #1: sector and #2: subsector
<form method="GET">
<div class="selectsector">
<Select class="selectsector" name = "sector">
#foreach($sectors10 as $sector)
<option>{{ $sector->SectorName }}</option>
#endforeach
</select>
<Select class="selectsubsector" name = "subsector">
#foreach($subsectors42 as $subsector)
<option>{{ $subsector->SectorName }}</option>
#endforeach
</select>
</form>
Routes:
Route::get('kitysoftware/besttrades', 'SectorsController#selectsector');
Route::get('kitysoftware/besttrades', 'SectorsController#selectsubsector');
Getting error: Undefined variable: sectors
Ok, i managed to do it using javascript and ajax function with json datatype. I'm new at JavaScript and it took me a while so i'm taking the time to publish the details for the newcomers. Here we go:
The View file:
The trick is to use a html hidden object that captures a route + prefix like in this line before the dropdowns:
<input type="hidden" name="application_url" id="application_url" value="{{URL::to(Request::route()->getPrefix()) }}"/>
The name of this object is "application_url" which we'll be using later in the javascript code to complete the url that the routes needs.
DropDown#1 with name "sectorSelect":
<label class="selectsector">Sector:</label>
<Select class="selectsector" id="sectorSelect" name="sectorSelect" >
<option value=""> -- Please select sector --</option>
#foreach ($sectors10 as $sector)
<option value="{{ $sector->SectorID }}">{{ $sector->SectorName }}</option>
#endforeach
</select>
DropDown #2 with name: "SubsectorSelect"
<label class="selectsector">SubSector:</label>
<Select class="selectsector" id="subSectorSelect" name="subSectorSelect">
<option value=""> -- Select an option --</option> // you don't have to do nothing here since this will be populated it from a query depending on the dropdown#1 selected value
</select>
Now in the web.php routes file:
Route::get('kitysoftware/sectors/subsectors/{id}', 'SectorsController#selectsubsector');
We are creating a route with an {id} parameter. This will be the selected value in dropdown #1. Then we call the "selectsubsector" method in the Sectorscontroller.
Controller:
First dropdown query:
public function selectsector()
{
$sectors = DB::table('Sectors')->select('SectorName', 'SectorID')-
>whereBetween('SectorID', [1, 10])->get();
return view('besttradesview', ['sectors10' => $sectors]);
Second Dropdown query (selectsubsector method):
public function selectsubsector($sectorId)
{
$subsectors = DB::table('Sectors')->select('SectorName', 'SectorID')->where('parentid', $sectorId)->get();
return response()->json($subsectors); //this line it's important since we are sending a json data variable that we are gonna use again in the last part of the view.
}
Final part of the view file The javaScript + ajax function
<script type="text/javascript">
$('#sectorSelect').change(function () { //we watch and execute the next lines when any value from the dropdown#1 is selected
var id = $(this).val(); //we get the selected value on dropdown#1 and store it on id variable
var url = $('#application_url').val(); //we get the url from our hidden element that we used in first line of our view file, and store it on url variable
//here comes the ajax function part
$.ajax({
url: url + "/kitysoftware/sectors/subsectors/" + id, //we use the same url we used in our route file and we are adding the id variable which have the selected value in dropdown#1
dataType: "json", //we specify that we are going to use json type of data. That's where we sent our query result (from our controller)
success: function (data) { //*on my understanding using json datatype means that the variable "data" gets the value and that's why we use it to tell what to do since here.*
//and this final part is where we use the dropdown#1 value and we set the values for the dropdown#2 just adding the variables that we got from our query (in controllert) through "data" variable.
$('#subSectorSelect').empty();
$.each(data, function (key, value) {
$('#subSectorSelect').append('<option value="' + key.SectorID + '">' + value.SectorName + '</option>');
});
}
});
});
</script>
Hope it helps the solution and the explanations. I'm happy to get some feedback as well.
I hope it is your requirement:
<Select class="selectsector" onChange="getSelectorValue( this, '#selector2' )" id="selector1" name="sector">
#foreach($sectors10 as $sector)
<option>{{ $sector->SectorName }}</option>
#endforeach
</select>
<Select class="selectsubsector" onChange="getSelectorValue( this, '#selector1' )" name = "subsector" id="selector2" >
#foreach($sectors10 as $sector)
<option>{{ $sector->SectorName }}</option>
#endforeach
</select>
Add Script to make it work:
<script type="text/javascript">
function getSelectorValue( selectorObj, selector ){
document.querySelector( selector ).value = selectorObj.value;
}
</script>
Controller
public function selectsector()
{
$sectors = Sector::get();
return view('besttradesview', compact('sectors'));
}
public function selectsubsector($sectors)
{
$subsectors = Sectors::where('parentid', $sectors)->get();
if (empty($subsectors)) {
$html = '';
$html = '<option value="">There has no Value</option>';
} else {
$html = '';
foreach ($subsectors as $subsector) {
$html .= '<option value="'.$subsector->id.'">'.$subsector->subsector.'</option>';
}
}
return response()->json(['html' => $html]);
}
route
Route::get('/get-selector/{id}', 'Inventory\selectorController#selectsubsector')->name('get.selector');
ajax
$(document).on('change','.selectsector',function () {
var id= $(this).val();
var url = "{{ URL::to('/get-selector') }}"+ '/' + id;
$.ajax({
url: url,
type: 'get',
dataType:'JSON',
success: function (response) {
console.log(response);
if(response.html==''){
$('.selectsubsector').html('<option value="">There has no Value</option>');
}else{
$('.selectsubsector').html(response.html);
}
},error: function (exception) {
console.log(exception);
}
});
});
I'm new to AngularJs and having some struggle.
Angular App:
// getting specs category
$http({
method: 'POST',
url: 'http://localhost/sjb/public/admin/angular/events/deelnemers/edit/specs',
data: {'specid': 11}
}).then(function successCallback(response){
$scope.SpecCategory = response.data;
console.log($scope.SpecCategory);
}, function errorCallback(response) {
alert("Fout met ophalen specs ID 11.");
});
Front-end
<select name="category" ng-model="user.cat_id">
<option ng-repeat="Cat in SpecCategory" ng-selected="Cat.spec_value == editEventUser.cat_id" value="{{Cat.spec_value}}">{{ Cat.spec_name }}</option>
</select>
values
Cat.spec_value = 1
editEventUser.cat_id = 1
But the option is not "selected" ?
Please help; what is wrong that
ng-selected="Cat.spec_value == editEventUser.cat_id"
Doesn't work?
The answer may be in the documentation for ng-select:
Note: ngSelected does not interact with the select and ngModel
directives, it only sets the selected attribute on the element. If you
are using ngModel on the select, you should not use ngSelected on the
options, as ngModel will set the select value and selected options.
Given your current code if you want to use ng-model, you have to remove ng-selected and make it so that user.cat_id is used to match one value in you select.
<select name="category" ng-model="user.cat_id">
<option ng-repeat="Cat in SpecCategory" value="{{Cat.spec_value}}">{{ Cat.spec_name }}</option>
</select>
I've been searching for similar question in a while but I couldn't find what would actually help my issue.
Using Laravel 5.4.
So I have a resource controller and its index method that returns a view with some data attached to it.
Then I want to make an ajax request from the view returned which is a search request.
e.preventDefault();
let q = $('#inputserver').val();
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$.ajax({
url: "/servers",
type: 'GET',
data: {'data': q},
success: function(response){
console.log('Successo');
}
})
That, for how a resource controller's methods are structured should invoke the index method, in which I want to identify if I have an Ajax request incoming.
If I do, I'll search with a query in an Eloquent Model for the data retrieved by the search form and of course I want to show only the matching results.
This is my controller code:
if(!$request->ajax()){
$colonna = 'id';
$servers = Server::orderBy($colonna, 'desc')->paginate(10);
return view('servers.index', array('servers' => $servers));
}
else{
$servers= Server::where('name', '=', $request->data)->paginate(10);
return view('servers.index', array('servers' => $servers));
}
The issue is that nothing is happening, so the ajax request isn't even considered, can someone help me with this? I'm almost sure the issue is some obvious things I forgot or didn't consider.
Thank you in advance, I'll edit if you would need some more info about it.
EDIT:
This is the route I have Route::resource('servers', 'ServerController');
EDIT2:
I'm sorry ids are in Italian, but I of course select them correctly when using jQuery.
<div class="input-group mb-2 mr-sm-2 mb-sm-0">
<div class="input-group-addon">
<span>
<i class="fa fa-search"></i>
</span>
</div>
{{Form::text('search', null, array('class' => 'form-control', 'id' => 'inputserver' , 'placeholder' => 'Cerca..'))}}
<span class="input-group-btn">
<button class="btn btn-default" type="button" id="cercaserver">Go!</button>
</span>
The blade file is messy.Try to create a form open and form close and make the button submit of type. And try to change your ajax to this:
$(document).ready(function() {
$('#cercaserver').on('submit', function (e) {
e.preventDefault();
var input = $('#inputserver').val();
$.ajax({
type: "GET",
url: './servers',
data: {input: input},
});
});
});
make sure you are loading jquery.
What do you mean by nothing's happening? What was shown in the console when the ajax request was fired?
Also, you're returning a view, you might want to return a json array of your results?
return $servers;
Laravel will automagically convert it into a JSON response
https://laravel.com/docs/5.4/responses#creating-responses
Or if you want to be specific:
return response()->json($servers);
https://laravel.com/docs/5.4/responses#json-responses
Edit:
I think I already know the problem, in your resource controller function index, is there a parameter called $request? It might be non existing and for sure will throw a 500 internal server error because you used it in your condition.
I found how to accomplish this on another site and I got it working. My issue is though that I need to use it in my edit form (preferably in the same form as my create form, since my create and edit views use the same form). When I go to my edit page, the "Section" dropdown value is selected as it should be. But the "Subsection" is not, because ofcourse I did not click it. Probably it's a fix too easy for me to see, but I am not quite good with javascript. I basically need the second dropdown (the subsection one) to show the correct options based on which "section" (first dropdown) is selected, on my edit view.
Section Model:
public function subsections()
{
return $this->hasMany('App\Subsection');
}
Subsection Model:
public function section()
{
return $this->belongsTo('App\Section');
}
View:
{!! Form::select('section_id', [null=>'-- Select Section --'] + $sections, null, array('id' => 'section')) !!}
<select id="subsection" name="subsection_id" class="select">
<option>-- First Select Section --</option>
</select>
From my controller: $sections = Section::lists('section', 'id');
Script:
<script>
$(document).ready(function($){
$('#section').change(function(){
$.get("{{ url('api/dropdown')}}",
{ option: $(this).val() },
function(data) {
$('#subsection').empty();
$.each(data, function(key, element) {
$('#subsection').append("<option value='" + key +"'>" + element + "</option>");
});
});
});
});
</script>
Route:
Route::get('api/dropdown', function(){
$id = Input::get('option');
$subsections = Section::find($id)->subsections;
return $subsections->lists('subsection', 'id');
});
If you just want to select the first option in jquery , you can add :
$('#subsection option:eq(1)').prop('selected', true);
Or else if you want to select a particular value, you can do that by
$('#subsection option[value="value_to_be_selected"]').prop('selected', true);
Use this after you have appended all the values to the subsection
In my controller I added:
$subsections = Subsection::where('section_id', '=', $transaction->section_id)->orderBy('subsection', 'asc')->lists('subsection', 'id');
And in my view I did this:
#if(isset($transaction))
{!! Form::select('subsection_id', [null=>'-- Select Subsection --'] + $subsections, null, array('class' => 'select', 'id' => 'subsection')) !!}
#else
<select id="subsection" name="subsection_id" class="select">
<option>-- First Select Section --</option>
</select>
#endif
Problem solved :)
So, what we will do is initially we will send value to the dependent drop-down as "<option value="">Select Something</option>"
and when returning on error create complete drop-down with selected as below value and return, this will reduce lots of javascript calls.
Controller:
if($error){
//create get array of second drop-down, suppose $second_drop
// create complete second drop-down like
$selectbox="";
foreach($second_drop as $option){
$selectbox.="<option value='". $option->id."'";
if($request->option2==$ $option->id){
$selectbox.=" selected ";
}
$selectbox.=">".$option->value."</option>";
}
}
return view('routename', ['selectbox2' => $selectbox]);
View:
<select id="subsection" name="subsection_id" class="select">
{!! $selectbox !!}
</select>