Select2 v4 Result does not show in the dropdown - php

What could be wrong in the code below?
I'm using Select2 version 4, when there's no result the No result dropdown shows,
But when there's result nothing shows (The dropdown does not show).
function formatProduct(product) {
if (product.loading) return product.text;
var markup = '<div class="product-to-compare" data=' + product.id + '>' + product.text + '</div>' ;
return markup;
}
function formatProductSelection(product) {
return product.name || product.text;
}
$(".select-category").select2({
ajax: {
url: "/autocomplete",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
minimumInputLength: 3,
templateResult: formatProduct,
templateSelection: formatProductSelection
});
In the result from php script I have something like this:
{"items":{"id":12,"text":"Sport"}}
But the dropdown does not show, is there something wrong I'm doing?

Related

How to disable click when autocomplete Field "no rseult found" via ajax call

I have done almost everything and I have successfully implemented autocomplete searching with ajax. Now problem is that when no data is found in autocomplete searching by default it shows No Result found. When I click on "NO Results Found" it is appearing on textbox. I want when No Results Found and user tries to click on that it should be no clickable
Here is My jquery Code:
src = "{{ route('searchajax') }}";
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
});
And My laravel 5.2 function
public function autoComplete(Request $request) {
$query = $request->get('term','');
$states=DB::table('states')->where('state','LIKE','%'.$query.'%')->get();
$data=array();
foreach ($states as $state) {
$data[]=array('value'=>$state->state,'id'=>$state->id);
}
if(count($data))
return $data;
else
return ['value'=>'No Result Found','id'=>''];
}
This is the answer you are looking for
You can use the response function to check if you do have results. If not, just push "No results found" to your list and then use _renderItem to disable this option.
$("#search_text").autocomplete({
source: function(request, response) {
$.ajax({
url: src,
dataType: "json",
data: {
term : request.term
},
success: function(data) {
response(data);
}
});
},
min_length: 3,
response: function(event, ui) {
if( ui.content.length === 0 ) {
ui.content.push({
'label': 'No results found',
'value': ''
});
}
}).data("ui-autocomplete")._renderItem = function(ul, item) {
if( item.value == '' ) {
return $('<li class="ui-state-disabled">'+item.label+'</li>').appendTo(ul);
} else {
return $("<li>").append("<a>" + item.label + "</a>").appendTo(ul);
}
};
I made this fiddle so you can see it working.

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');
}

Select2 Ajax Laravel - results not showing

JS
$("#location").select2({
ajax: {
url: "/search/locations",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1,
placeholder: function(){
$(this).data('placeholder');
}
});
Controller
public function searchLocations()
{
$q = Input::get('q');
$results = Location::where('suburb', 'LIKE', '%'. $q . '%')
->orWhere('state', 'LIKE', '%'. $q . '%')
->orWhere('postcode', 'LIKE', '%'. $q . '%')
->get();
return Response::json( $results );
}
I can see the ajax request being made, and recieving data back, but it doesn't show the results. I'm using the latest version of Select2 (v4.0.2)
When you're loading custom data from a remote source, Select2 doesn't typically know what to do with them. You'll need to specify how each result is formatted by setting a templateSelection for the options and a templateResult for the selected option like so:
function locationResultTemplater(location) {
return location.suburb + " " + location.state + " " + location.postcode;
}
function locationSelectionTemplater(location) {
if (typeof location.suburb !== "undefined") {
return locationResultTemplater(location);
}
return location.text; // I think its either text or label, not sure.
}
$("#location").select2({
ajax: {
url: "/search/locations",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
minimumInputLength: 1,
placeholder: function(){
$(this).data('placeholder');
},
templateResult: locationResultTemplater,
templateSelection: locationSelectionTemplater
});
Note that in order to return HTML mark-up instead just plain text you'll need to have the template function return a jQuery object selector e.g. return $("<div class='styleme'>Content</div>);

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

Select2 AJAX Multiple not working properly

So i have a select2 ajax selector that works perfectly when not using multiple , but when I use multiple it basically sometimes it works , others it doesn't.
$('#organizations').select2(
{
placeholder: "Add Organizations!",
minimumInputLength: 3,
multiple: true,
ajax: {
url: "https://boilerprojects.com/organizations/search",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term, // search term
page_limit: 10
};
},
results: function (data, page)
{
var more = (page * 10) < data.total;
console.log(data.results);
return { results: data.results, more: more };
},
dropdownCssClass: "bigdrop"
},
});
what returns from my PHP is : {"results":[{"id":"6","text":"LukePOLO"}]}
So im getting results its just not populating.
Anyone have any ideas?
If you want to use that infinite scroll option, then your response is wrong.
{"results":[{"id":"6","text":"LukePOLO"}]}
should be something like:
{"results":[{"id":"6","text":"LukePOLO"}], "total":"1"} //Total 1 result
you have key results but do not have a key for total. And in your post data function you should allso say witch page you search.
$('#organizations').select2(
{
placeholder: "Add Organizations!",
minimumInputLength: 3,
multiple: true,
ajax: {
url: "https://boilerprojects.com/organizations/search",
dataType: 'json',
quietMillis: 100,
data: function (term, page) {
return {
q: term,
page_limit: 10,
page: page //you need to send page number or your script do not know witch results to skip
};
},
results: function (data, page)
{
var more = (page * 10) < data.total;
return { results: data.results, more: more };
},
dropdownCssClass: "bigdrop"
}
});

Categories