What options I should set to get the value of the options when I submit the form?
I am using Select2. I have given the code I have to setup the select2, controller that returns the data, the html code that renders the element.
Html Code to add the select2 element:
<div class="form-group row"><label class="col-lg-2 col-form-label">Keyword</label>
<div class="col-lg-10">
<select class="form-control w-50" name="keywords[]" id="keyword" multiple="multiple">
</select>
<span class="form-text m-b-none">One or multiple keywords</span>
</div>
</div>
Datasource is an Ajax call:
$(document).ready(function() {
$('#keyword').select2({
tags: true,
tokenSeparators: [',', ' '],
placeholder: 'Select keyword',
ajax: {
url: 'https://rankypro.dev/app/json/keywords',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
cache: true
}
});
Controller:
public function getKeywords(Request $request){
$search = $request->search;
if($search == ''){
$keywords = Term::orderby('name','asc')
->select('id','name')
->where('taxonomy','keyword')
->limit(5)
->get();
}else{
$keywords = Term::orderby('name','asc')->select('id','name')
->where('taxonomy','keyword')
->where('name', 'like', '%' .$search . '%')
->limit(5)
->get();
}
$results = array();
foreach($keywords as $keyword){
$results[] = array(
"id"=>$keyword->id,
"text"=>$keyword->name
);
}
echo json_encode($results);
exit();
}
I am testing with:
public function store(Request $request)
{
dd($request->keywords);
}
I get the following:
array:2 [
0 => "Tools"
1 => "SEO"
]
I actually need ids of the keywords. Would you please give some hints how can I get that.
I think their is some issue in rendering data. Try to replace
processResults: function (data) {
return {
results: $.map(data, function (item) {
return {
text: item.name,
id: item.id
}
})
};
},
With
processResults: function (data) {
return {
results: data.item
};
},
select2 automatically render id and name.
Related
hello i'm trying to use select2 on a laravel 8 website i'm creating.
it is working correctly but when i submit the form it saves on the database the id instead of the name. (i need to store the name "origem" instead of the id of "origem".
the code is this:
create.blade
<div class="container mt-5">
<div class="row">
<div class="form-group mb-3">
<select class="origem form-control p-3" name="origem"></select>
</div>
</div>
</div>
<script type="text/javascript">
$('.origem').select2({
placeholder: 'Select movie',
ajax: {
url: 'ajax-autocomplete-search',
dataType: 'json',
delay: 250,
processResults: function(data) {
return {
results: $.map(data, function(item) {
return {
text: item.origem,
id: item.id
}
})
};
},
cache: true
}
});
</script>
selectsearch controller
public function selectSearch(Request $request)
{
$origem = [];
if($request->has('q')){
$search = $request->q;
$origem = Origem::select("id", "origem")
->where('origem', 'LIKE', "%$search%")
->get();
}
return response()->json($origem);
}
form controller
$data->origem = $request->input('origem');
$data->save();
I want to show a data controller to view using ajax and I have already shown a data controller to view on the chart bar without ajax I need to get data on the chart bar using ajax but I don't have an idea how to show data on chart bar using ajax.
I don't have that good experience in JSON/AJAX/Laravel, I'm a beginner.
Controller
public function index()
{
$manager_hourlog = Hourlog::with('project', "user")->get()-
>groupBy('project.name');
$projects = [];
$totals = [];
foreach ($manager_hourlog as $key => $val) {
$projects[] = $key;
}
foreach ($manager_hourlog as $key2 => $val) {
$minutes = $val->sum('hour_work');
$totals[] = round($minutes / 60, 1);
}
$users = User::where("status", 1)->get();
$data = [
// manager report
'manager_projects' => $projects,
'totals' => $totals,
"manager_hourlog" => $manager_hourlog,
"auth" => $auth,
];
return response()->json(['data' => $data]);
return view('cms.dashboard', $data);
}
Script
<script>
// Employee report script
var colors = ["#1abc9c", "#2ecc71", "#3498db",
"#9b59b6", "#34495e", "#16a085", "#27ae60"];
#if ($auth->user_type != 1)
// manager report script
var managerchartbar = {
labels: {!! json_encode($manager_projects) !!},
datasets: [
#foreach($users as $user)
{
label: {!! json_encode($user->name) !!},
backgroundColor: colors[Math.floor(Math.random() * colors.length)],
// data: [300,200,500,700]
data: [
#foreach($manager_hourlog as $hourlog)
{{$hourlog->where("user_id", $user->id)->sum("hour_work") / 60}},
#endforeach
]
},
#endforeach
]
};
var ctx = document.getElementById('manager').getContext('2d');
window.myBar = new Chart(ctx, {
type: 'bar',
data: managerchartbar,
options: {
title: {
display: true,
text: 'Employees Report chart'
},
tooltips: {
mode: 'index',
intersect: false
},
responsive: true,
scales: {
xAxes: [{
stacked: true,
}],
yAxes: [{
stacked: true
}]
}
}
});
#endif
ajax
$.ajax({
type: 'GET',
url: '{{url("/dashboard")}}',
data: {
data: data
},
success: function(data){
console.log(data.data);
},
error: function(xhr){
console.log(xhr.responseText);
}
});
</script>
Html VIew
<div class="col-md-12">
<div class="card-box">
<div class="container-fluid">
<canvas id="manager" height="100">
</canvas>
</div>
</br>
</div>
</div>
Route
Route::get('/dashboard',
'DashboardController#index')->name('dashboard');
Here is my problem.
I'm trying to fetch the data from an auto-completing text-box.
There are two text-boxes:
Region and province.
I have successfully fetched the data on the text-box having region as name.
My problem is, it gives the same value to the next text-box having province as name.
In my Laravel blade I have this code:
<input id="region" type="text" class="form-control" name="region" value="" required autofocus>
<div id="regionList"> </div>
<input id="province" type="text" class="form-control" name="province" value="" required autofocus>
<div id="provinceList"> </div>
I have also a javascript file named auto-complete
$(document).ready(function() {
$('#region').keyup(function() {
var region = $(this).val();
if (region != '')
{
var _token = $('input[name="_token"]').val();
$.ajax({
url: "register/showRegion",
method: "POST",
data: { region: region, _token: _token },
success: function(data)
{
$('#regionList').fadeIn();
$('#regionList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
$('#province').keyup(function() {
var province = $(this).val();
if (province != '')
{
var _prov_token = $('input[name="_token"]').val();
$.ajax({
url: "register/showProvince",
method: "POST",
data: { province: province, _token: _token },
success: function(data)
{
$('#provinceList').fadeIn();
$('#provinceList').html(data);
}
});
}
});
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
});
And on my routes I included this
Route::post('/register/showRegion', 'LocationController#showRegion');
Route::post('/register/showProvince', 'LocationController#showProvince');
And on my controller is this
public function index() {
return view('auth.register');
}
function showRegion(Request $request)
{
if ($request->get('region'))
{
$region = $request->get('region');
$regions = Refregion::where('regDesc', 'LIKE', "$region%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($regions as $region)
{
$output .= '<li>'.$region->regDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
function showProvince(Request $request)
{
if ($request->get('province'))
{
$province = $request->get('province');
$province = Refprovince::where('provDesc', 'LIKE', "province%")->get();
$output = '<ul class="dropdown-menu" style="display:block; position:absolute;">';
foreach($provinces as $province)
{
$output .= '<li>'.$province->provDesc.'</li>';
}
$output .= '</ul>';
echo $output;
}
}
I'm trying to figure out why it gives the same value to the other text-box "province" when I have selected region.
Can someone help me with this, or at least explain to me why this happen?
Thank you
change it
$(document).on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
on this
$('#regionList').on('click', 'li', function() {
$('#region').val($(this).text());
$('#regionList').fadeOut();
});
and change it
$(document).on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
on this
$('#provinceList').on('click', 'li', function() {
$('#province').val($(this).text());
$('#provinceList').fadeOut();
});
I have a search place for costumers to search the product which will be displayed in blade. I am using ajax and laravel. Here is my code as much as I wrote. The query works well and when I print $filter I can see the results.
$('.gotosearch').on('click' , function() {
var search = $(this).val()
var inpvalue = $('.form-control').val()
$.ajax({
url:'/searchproducts',
type:'post',
data: {
inpvalue,
"_token" : token
},
success:function(r) {
console.log(r)
}
})
})
Route::post('/searchproducts' , 'ProductController#searchproducts');
function searchproducts(Request $search) {
$filter = ProductModel::where('Product_Name','LIKE', $search->inpvalue.'%')->get();
}
You can use response()->json in you controller
As per Laravel documentation
The json method will automatically set the Content-Type header to
application/json, as well as convert the given array to JSON using the
json_encode PHP function:
return response()->json([
'name' => 'Abigail',
'state' => 'CA'
]);
Try this:
return response()->json($filters->toArray());
https://laravel.com/docs/5.8/responses#json-responses
try this:
// search text
<div class="form-group">
<input type="text" id="search" name="search" class="form-control" id="exampleInputEmail" aria-describedby="emailHelp" placeholder="Search" value="{{ old('accountNo') }}" style="font-size:20px;font-weight:bold;" required>
</div
// search result
<div id="getResult" class="panel panel-default" style="width:400px; height: 150px; overflow-y:auto; position:absolute; left:50px; top:180px; z-index:1; display:none;background-color:white">
<div id="getList"></div>
</div>
//ajax
$.ajaxSetup({
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
}
});
$('#search').keyup(function(){
var search = $('#search').val();
if(search==""){
$('#getResult').css('display', 'none').hide();
}
else{
var getQueries = "";
$.get("{{ url('/') }}" + '/search/' + search,
{search:search},
function(data){
if(data){
$('#getResult').css('display', 'block');
}else{
$('#getResult').css('display', 'none')
}
if(search == ''){
$('#getResult').css('display', 'none').hide();
}else{
$.each(data, function (index, value){
var id=value.ID;
getQueries += '<ul style="margin-top:3px; list-style-type:none;">';
getQueries += '<a href={{ url("add-contribution-amount")}}' +'/'+ value.id + '>' + value.fullname +' | '+value.accountno + '</a>';
getQueries += '</ul>';
});
$('#getList').html(getQueries );
}
})
}
});
</script>
//controller
public function CustomerSearch($getSearch){
$search = $getSearch;
$members = DB::table('tblcustomers')
->where('accountno', 'like', "%$search%")
->select('id','branchID', 'fullname', 'savingstype', 'accountno')
->orderby('id','asc')
->get();
return $members;
}
//route
Route::get('/search/{searchQuerys?}', 'ContributionController#CustomerSearch');
I need to add a Laravel Dynamic Dependent Dropdown. Im confused..
In my database, i have both categories and their childrens.
Account_id =0 => Categorie
Account_id =1 => Sub Categorie of category or subcategory with id =1
Account_id =2 => Sub categorie of category or subcategory with id =2
This is my actual code :
Method:
public function index()
{
$categories = Account::where('account_id', '=', 0)->get();
$allCategories = Account::where('account_id', '=', 0)-
>pluck('account_name','id');
return view('Account.list',compact('categories', 'allCategories')); //
set the path of you templates file.
}
public function children(Request $request)
{
return Account::where('account_id', $request->account_id)->pluck('account_name', 'id');
}
View:
<div class="form-group">
{!! Form::label('account_id', 'Parent Category:')!!}
{!! Form::select('account_id', $allCategories, ['placeholder' =>
'Choose Category'])!!}
</div>
<div class="form-group">
{!! Form::label('children', 'Child category:')!!}
{!! Form::select('children', [], null, ['placeholder' => 'Choose child
category'])!!}
</div>
Route:
Route::get('/categories', [
'uses' => 'AccountController#index',
'as' => 'categories'
]);
Route::get('/categories/children', [
'uses' => 'AccountController#children',
'as' => 'categories.children'
]);
JS:
<script>
$('#account_id').change(function(e) {
var parent = e.target.value;
$.get('/categories/children?account_id=' + account_id, function(data) {
$('#children').empty();
$.each(data, function(key, value) {
var option = $("<option></option>")
.attr("value", key)
.text(value);
$('#children').append(option);
});
});
});
</script>
try this first create new route
Route::post('subchildren/youcontroller', [
'as' => 'children.categories',
'uses' => 'youUrlController\yourController#childrenCategory',
]);
next create route go to controller create new method
public function childrenCategory(Request $request)
{
try {
$subCategory= subCategory::where('category_id', $request->nameSelectCategoryinYourView)->get();
return response()->json(['subCategory' => $subCategory], 200);
} catch (Exception $e) {
return response()->json(['error' => 'Error'], 403);
}
}
next in your view
<div class="form-group m-b-40">
<select name="subCategory" class="form-control p-0" id='subCategory'></select>
</div>
next in your javascript
jQuery(document).ready(function($) {
$('#FirstSelect').change(function () {
$('#subCategory').empty();
var Category = $(this).val();
datos = {
tipo : Category
},
$.ajax({
url: '{{ route('children.categories') }}',
type: 'POST',
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: datos,
success: function (argument) {
arreglo = {id:"a", tipo:""};
argument.detalles.unshift(arreglo);
$.each(argument.subCategory, function(index, el) {
var opcion = '<option value="'+ el.id +'">'+ el.subCategoryName+'</option>';
$('#subCategory').append( opcion );
});
}
})
.done(function() {
console.log("success");
})
.fail(function() {
console.log("error");
})
.always(function() {
console.log("complete");
});
})
});
});