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>);
Related
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.
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');
}
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?
I am trying to implement xeditable plugin select2 with emote data fetch from my database , my data fetch script is returning the json data but the ajax call is not retrieving it . my code looks like the following:
HTML
found by ID
Javascript
$('#username ').editable({
type: 'select2',
url: '../payments/person.php',
pk: 1,
onblur: 'submit',
emptytext: 'None',
select2: {
placeholder: 'Select a Requester',
allowClear: true,
width: '230px',
minimumInputLength: 3,
id: function (e) {
return e.person_id;
},
ajax: {
url: '../payments/person.php',
dataType: 'json',
data: function (term, page) {
return { query: term };
},
results: function (data, page) {
return { results: data };
}
},
formatResult: function (employee) {
return employee.name;
},
formatSelection: function (employee) {
return employee.name;
},
initSelection: function (element, callback) {
return $.get('../payments/person.php', { query: element.val() }, function (data) {
callback(data);
}, 'json'); //added dataType
}
}
});
Php code returns the data in json format like below:
[{"id":"1","name":"AdminAdmin"}]
I am sure my ajax code is not collecting the data properly , and when i click on it it doesnt load the popup as well. if someone could help.
my php code for fetching look like the following:
if (isset($_POST['person_id'])) {
$id = trim($_POST['person_id']);
$result = array();
$id = mysqli_real_escape_string($con,$id);
$res = mysqli_query($con,"SELECT person_id,Concat(first_name ,last_name) as name FROM k_people ");
while ($row = mysqli_fetch_array($res)) {
$result[] = array(
'id' => $row['person_id'],
'text' => $row['name']
);
}
echo json_encode($result);
}
I think [{"id":"1","name":"AdminAdmin"}] should be [{"id":"1","text":"AdminAdmin"}].
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