Populating a column from database into select2 via jquery - php

I'm trying to populate tags from DB into a select2 field. The data is returned in the inspect mode, but not populating in the select2 field.
I have a tags table with the tag_id and tag_name fields. The following is the code from the controller that fetches and returns the tags :
public function getTag()
{
$tag_list = DB::table('tags')
->select('t_name')
->get();
return response()->json(['tag_n' => $tag_list]);
The following is the Jquery that brings back the tags :
<script>
$(document).ready(function() {
$("#catBox").select2({
placeholder:"Select and search",
ajax:{
url: urlTag ,
type: 'GET' ,
dataType: 'json',
delay: 250,
data:function(params){
return{
tag_n:params.term
};
},
processResults:function(response){
return{
results: response
};
},
cache:true
}
});
});
</script>
The route and the route url :
<script>
var urlTag = '{{ route('getTag') }}';
</script>
Route::get('/gettag', [
'uses' => 'PostController#getTag',
'as' => 'getTag'
]);
The data is returned in the inspect mode, but not populating in the select2 field.
The following is the Select tag :
<select class="js-example-basic-multiple" multiple="multiple" name="catBox[]" id="catBox" style ="width:250px">
</select>

return data from a server like this:
[{t_name : "PHP"},{t_name : "TEST"},{t_name : "DEMO"}] insted of pass with `{a_tag : [{t_name : "PHP"},{t_name : "TEST"},{t_name : "DEMO"}]}`
$("#catBox").select2({
tags: true,
tokenSeparators: [",", " "],
createSearchChoice: function(term, data) {
if ($(data).filter(function() {
return this.text.localeCompare(term) === 0;
}).length === 0) {
return {
t_name: term
};
}
},
multiple: true,
ajax: {
url: urlTag ,
dataType: "json",
data: function(term, page) {
return {
q: term
};
},
results: function(data, page) {
return {
results: data
};
}
}
});

Related

Can't attach data to select2 option

I want to make edit form and attach data from database to select2 option. In insert form this select2 option search data in database when we type word by word. I can't attach the data in this select2 option. I want to make this select2 option is fill with the data from database and also can change the data like in insert form. I already try $('#requestor').val($row['requestor']); but the data doesn't appear. Can anyone help me???
<select class="requestor form-control" name="requestor" id="requestor" style="width:700px" required="required">
<option value=""></option>
</select>
//search data in database word by word
$('.requestor').select2({
placeholder: 'Requestor Name',
ajax:{
url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
dataType: "json",
delay: 250,
processResults: function(data){
var results = [];
$.each(data, function(index, item){
results.push({
id: item.ID,
text: item.FullName,
option_value:item.ID
});
});
return{
results: results,
cache: true,
};
},
}
});
function load() {
alert('ok');
//console.log(<?php echo $row['ID']; ?>);
if (<?php echo $row['ID']; ?> != '') {
$('#requestor').val($row['requestor']);
}
}
window.onload = load;
Thank You :)
Your code is very messy. Be more clear like this:
<div class="col-md-12">
<select style="width:100%;" name="requestor[]" id="requestor" class="select2-multiple" multiple></select>
</div>
Then:
var $ajax = $("#requestor");
$ajax.select2({
ajax: {
url: "<?php echo base_url('Hire_4/select_personnel'); ?>",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return{
search: params.term
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data
};
},
cache: true
},
language: "en",
placeholder: "Requestor Name",
allowClear: true,
minimumInputLength: 3,
maximumSelectionLength: 1,
escapeMarkup: function (markup) { return markup; },
templateResult: formatRepo,
templateSelection: formatRepoSelection
});
function formatRepo(repo) {
var markup = repo.text ;
return markup;
}
function formatRepoSelection (repo) {
return repo.Name.replace(/<\/?("[^"]*"|'[^']*'|[^>])*(>|$)/g, "");
}
Your Ajax data must be have this format:
data[0]['ID'] = 1; //You must have "ID" key
data[0]['Name'] = 'Name'; //You must have "Name" key
It's easy that's it!
Good luck.

Select2 with AJAX always no result found

Following tutorial Select2 with AJAX, I am trying retrieve students list with ajax. my input is :
<select class="form-control" id="student_id" name="student_id"></select>
and the script is :
var url = '';
url += "{{ route('api.student_list') }}";
console.log(url); //outputs http://localhost/project-child/public/api/get-students
$( "#student_id" ).select2({
placeholder: 'Select an item',
ajax: {
url: url,
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
The JSON response is similar to
[{"id":1,"text":"EJAJUL HAQUE"},{"id":2,"text":"MUSTAK AHMED"},{"id":3,"text":"AZAD HOQUE"},{"id":4,"text":"ANJARUL HAQUE"},{"id":5,"text":"ARIFUL ISLAM"},{"id":6,"text":"SANJITA KHATUN"},{"id":7,"text":"MARINA SULTANA"},{"id":8,"text":"SULTANA BEGUM"},{"id":9,"text":"SABINA KHATUN"},{"id":10,"text":"JENIFA AHMED"},{"id":11,"text":"REJUON AHMED"},{"id":12,"text":"FARITA KHATUN"},{"id":13,"text":"HABIJUL HOQUE"},{"id":14,"text":"JENIFA MUSKAN"},{"id":15,"text":"JOTUFA WAHID"},{"id":16,"text":"MAUSUMI BEGUM"},{"id":17,"text":"ABJARUL RAHMAN"},{"id":18,"text":"JANNATUR ANJU"},{"id":19,"text":"RIYAD "},{"id":20,"text":"RAJIBUL HOQUE"},{"id":21,"text":"UMME SALMA"},{"id":22,"text":"RAFIKUL ISLAM"},{"id":23,"text":"ABJAL HUSSAIN"},{"id":24,"text":"IMAM AHMED"},{"id":25,"text":"NARGIS SULTANA"},{"id":26,"text":"MAFUDA KHATUN"},{"id":27,"text":"SIDDIKUL NAHAR"},{"id":28,"text":"KHALEDA BEGUM"}]
But If I search , say EJAJ it says No results found. I am using select version 4.0.3
on processResults , count data and if its length == 0 then do smt ...
processResults: function (data) {
if(data.length==0){
getFromGoogle();
}
return {
results: data
};
},
Get rid of the whole processResults stuff and make your data server turn your JSON array a subarray with key results. This way:
{"results":[your-JSON-array-above]}

how to create Loading remote data search in Laravel 5.2?

This website is Book Hotel, After a user search to see the city and hotel.
I want to use Loading remote data select2 in laravel 5.2.
Github examples: https://select2.github.io/examples.html#data-ajax
Model City:
protected $fillable = [
'name', 'state', 'country', 'status'
];
Model Hotel:
protected $fillable =[
'name', 'address', 'phone', 'status', ...
];
HTML:
<select class="js-data-example-ajax">
<option value="3620194" selected="selected">select2/select2</option>
</select>
Script:
$(".js-data-example-ajax").select2({
ajax: {
url: "https://api.github.com/search/repositories",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// parse the results into the format expected by Select2
// since we are using custom formatting functions we do not need to
// alter the remote JSON data, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
How to write in Laravel controller after send data from ajax?
HTML:
<select id="hotel" name="hotel">
<option value="hotel1">Hotel1</option>
<option value="hotel2">Hotel2</option>
</select>
Jquery and Ajax:
$(document).on('click','#hotel',function(e)
{
e.preventDefault();
var name=$(this).val('hotel');
$.ajax({
type:"POST",
url: "{{url('/controller/search')}}",
data: {
"_token": "{{ csrf_token() }}"
},
success: function (data) {
var res = $.parseJSON(data);
if(res == true)
{
alert('ok');
}
}
});
});
Laravel Controller:
public function search(Request $request)
{
$hotel=Hotel::where(['name',$request->name])->first();
return Response::json(array('status'=>TRUE,'hotel'=>$hotel));
}

Setting value of select2, which uses AJAX, on page load

Is it possible to programmatically select an entry for a select2 that uses AJAX for its list build, using the entry's id?
I am using a select2 element in my page to get client information. The select2 uses AJAX to load the list of client names based on the user typing an input.
Once the user selects the client, I post to back end with client_id and run a search / generate a list of data, which is then loaded onto a new impression of the same page.
I want to pre-select the select2 with this client_id and have it show the relevant client_name. How do I get the AJAX based select2 to select this client_id?
My JS and select2 code is:
var resultsArray;
var clientSearch = '{!! $clientSearch !!}';
$(document).ready(function() {
$('#client_id').select2({
theme: 'bootstrap',
placeholder: 'Select client',
val: clientSearch, // TRIED THIS BUT IT DOES NOT WORK
ajax: {
url: '{!! route('client.selectList') !!}',
type: 'POST',
dataType: 'json',
delay: 500,
headers: {
'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
},
data: function (params) {
return {
term: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
resultsArray = data;
params.page = params.page || 1;
return {
results: $.map(data, function(obj) {
return {
id: obj.id, text: obj.client_name + ' (' + obj.state + ' ' + obj.postcode + ')'};
}),
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2
});
});
I have tried setting the val: (per above) and setting the select2 value like below without success:
if (clientSearch != null) {
$('#client_id').select2({'val': clientSearch});
}
if (clientSearch != null) {
$('#client_id').val(clientSearch).trigger("change");
}
if (clientSearch != null) {
$("#client_id").select2('data', {id: clientSearch, text: clientName});
}
I also tried another suggestion such as adding this to the select2 declaration as follows:
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2
}).val(clientSearch).trigger('change');
Thanks for any suggestions
I got the answer from here.
if (clientSearch != null) {
$('#client_id').append('<option value="' + clientSearch + '">' + clientName + '</option>');
$('#client_id').val($('#client_id').val()).trigger('change');
}

Add some default options in select2 when dropdown is open in remote data

I am using Select2 with remote data. when i click on drop-down. no option will shows until write in search box.
But i want to show some data when drop-down open.
I am trying it with initselection or data but its initialize when data present in selected value.
$('.countrySelection').select2({
placeholder: "Select Country",
allowClear: true,
minimumInputLength: 1,
ajax: { // instead of writing the function to execute the request we use Select2's convenient helper
url: base_url+'ajax_response/getCountry',
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term, // search term
page: page
};
},
results: function (data, page) {
$(".statenoSelect").select2("val", "");
$(".citynoSelect").select2("val", "");
var more = (page * 2) < data.page
return {
results: data.items,
more: more
};
},
cache: true
},
initSelection: function(element, callback) {
var id = $(element).val();
if (id !== "") {
$.ajax(base_url+'ajax_response/getCountry?id=' + id, {
dataType: "json"
}).done(function(data) { callback(data['items'][0]); });
}else{
$.ajax(base_url+'ajax_response/getCountry?default=true', {
dataType: "json"
}).done(function(data) { callback(data['items']); });
}
},
data:function(element, callback) {
callback(JSON.parse($(element).attr('data-selection')));
},
formatResult: repoFormatResult,
formatSelection: repoFormatResult,
dropdownCssClass: "bigdrop",
escapeMarkup: function (m) { return m; }
}).focus(function () { $(this).select2('open'); });
Its working with ajax, but how can I add options without search anything

Categories