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]}
Related
My script won't load any data in the Select2. I made a test.php with JSON data (which will be provided external after everything works. (test.php is my internal test)).
Output of test.php
[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]
jQuery script:
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
tags: [],
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/test.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
alert(data);
},
processResults: function(data) {
return {
results: $.map(data.suggestions, function(obj) {
return {
id: obj.key, text: obj.value
}
})
};
}
}
});
I have been searching and checking all other solutions. It it not working for me. I'm stuck.
Update: jQuery script so far
$("#billing_postcode_gemeente").select2({
minimumInputLength: 2,
placeholder: "Voer uw postcode in..",
ajax: {
url: 'https://www.vooronshuis.nl/wp-content/plugins/sp-zc-checkout/checkaddressbe.php',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (data) {
return {
ajax_call: 'addressZipcodeCheck_BE',
zipcode: '1200'
};
},
processResults: function(data) {
alert(data);
correctedData = JSON.parse(data)[0]suggestions;
alert(correctedData);
return {
results: $.map(correctedData, function(obj) {
return {
id: obj.key,
text: obj.value
}
})
};
}
}
});
Here is a working fiddle for your example.
I have done if on a local JSON object but you can replicate the same results on your response or maybe change your response accordingly.
Your data.suggestions is nothing. Because data is a JSON array whose first element is a JSON object with key suggestions and value an array of suggestions.
Run this code in your JQuery enabled browser console and you will undestand.
var data = '[{"suggestions": ["1200 Brussel","1200 Bruxelles","1200 Sint-Lambrechts-Woluwe","1200 Woluwe-Saint-Lambert"]}]';
JSON.parse(data)[0];
JSON.parse(data)[0].suggestions;
Also check this answer to see how a proper response should look like.
Updated answer:
Sending additional data to back-end:
$('#billing_postcode_gemeente').DataTable(
{
......
"processing" : true,
"serverSide" : true,
"ajax" : {
url : url,
dataType : 'json',
cache : false,
type : 'GET',
data : function(d) {
// Retrieve dynamic parameters
var dt_params = $('#billing_postcode_gemeente').data(
'dt_params');
// Add dynamic parameters to the data object sent to the server
if (dt_params) {
$.extend(d, dt_params);
}
}
},
});
Here dt_params is your additional parameter (the zipcode
that you wish to send to the server to get an appropriate response). This dt_params gets added to the datatable parameters and can be accessed in your back-end to appropriate the response.
There must be a place where you are taking the zipcode entry. On the listener of that input box you can add the below code to destroy and recreate the datatable to reflect the changes. This code will add key-value (key being zip_code) pair to the dt_params key in your request JSON:
function filterDatatableByZipCode() {
$('#billing_postcode_gemeente').data('dt_params', {
ajax_call: 'addressZipcodeCheck_BE',
zip_code : $('#some_imput_box').val()
});
$('#billing_postcode_gemeente').DataTable().destroy();
initDatatable();
}
Try this way
$(".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, page) {
// 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
return data.items;
},
cache: true
},
minimumInputLength: 1,
templateResult: formatRepo, // omitted for brevity, see the source of this page
templateSelection: formatRepoSelection // omitted for brevity, see the source of this page
});
I am using Bootstrap Typeahead (version: v2.0.0). I have result set through an ajax call and would like to show autocomplete list using value and one more attribute.
I have result set like:
{"res":[{"id":617,"value":"DESC: Admin responder comment","user_id":37,"status":1,"comment":"Hi {firstname},\n\nThis is testing.","firstname":"Tom's"},
{"id":625,"value":"DESC: my comment","user_id":37,"status":1,"comment":"Hi {first_name}, anther testing comment","firstname":"William's"}
]}
Autocomplete matching keyword with value attribute and populating it. But, I would like to match keyword with comment attribute as well.
I have tried matcher of typeahead and some solutions mentioned on SO as well but did not found useful. Tried one here: but getting error of "TypeError: Bloodhound is undefined" with that solution.
Please check code below used for autocomplete using result by ajax.
var typeahead_pre_written_xhr = null;
var search_keyword = function ( tid, txtElmt )
{
$( "#typeahead-input" ).typeahead({
items: 20,
source: function(typeahead, query) {
action_url = _base_url + "search/search_keyword/";
typeahead_pre_written_xhr = $.ajax({
cache: false,
type: "POST",
dataType: "json",
url: action_url + query,
data: { 'type': type },
error: function (request, status, error) { },
success: function(data) {
if( typeof data.res != 'undefined' && data.res != '' ) {
typeahead.process(data.res);
}
}
});
},
onselect: function() {
// Do stuff
}
});
};
Please help me to achieve this.
Content is not displaying is autocomplate list as you can see in screenshot below.
I am getting this response.
[{"emp_number":1,"fname":"Arslan","lname":"Hassan"},{"emp_number":2,"fname":"Muneeb","lname":"Janjua"
},{"emp_number":3,"fname":"hr","lname":"user"},{"emp_number":4,"fname":"test","lname":""} .......... REMOVED TO MAKE IT LOOK BETTER HERE .......]
My JS Code:
$( "#search-emp" ).autocomplete(
{
source: function (request, response)
{
var form_data = {
ajax : '1',
name : $("#search-emp").val(),
actioncall : 'search-emp'
};
$.ajax({
//contentType: "application/json",
type: "POST",
dataType: 'json',
url: "_ajax.php",
data: form_data,
success: function( data )
{
response( data );
}
});
},
minLength:3,
select:function(evt, ui)
{
alert(ui.item.emp_number);
}
});
I want to display fname and lname on selected into input field.
The problem it's because jQuery autocomplete wants to have 2 fields named label and value. The content from label will be displayed in the autocomplete.
Because your server return other name for the keys you have 2 options:
Change the server to return a json like:
[{"emp_number":1,"fname":"Arslan","lname":"Hassan", "label":"Arslan Hassan", "value": "Arslan Hassan"},....]
Or on the success callback from ajax create an array with this fields (label and value) and pass this array to response() callback.
You can find more informations here: http://api.jqueryui.com/autocomplete/#option-source
I'm using Select2 to populate a dropdown of UK Towns. As the UK Towns DB is huge I figured an AJAX call would be the best way to bring in the data.
I have built a post function and some PHP (In Codeigniter) to catch the query and parse it.
I can see the data is being posted and responded, But my Select2 is not populating with the data.
My jQuery for this is :
$("#areas").select2(
{
tags: [],
ajax: {
url: '/profile/get-towns',
dataType: 'json',
type: "POST",
quietMillis: 100,
data: function (term) {
return {
query: term
};
},
results: function (data) {
return {
results: data.town_id
}
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 4,
placeholder : "Start typing your Town / City",
maximumSelectionSize: 2
}
);
My response jSON (Example) is as follows :
[{"town_id":"16994","town":"Hartle"},{"town_id":"16995","town":"Hartlebury"},{"town_id":"16996","town"
:"Hartlebury"},{"town_id":"16997","town":"Hartlebury Common"},{"town_id":"16998","town":"Hartlepool"
},{"town_id":"16999","town":"Hartley"},{"town_id":"17000","town":"Hartley"},{"town_id":"17001","town"
:"Hartley"},{"town_id":"17002","town":"Hartley"},{"town_id":"17003","town":"Hartley Green"},{"town_id"
:"17004","town":"Hartley Green"},{"town_id":"17005","town":"Hartley Mauditt"},{"town_id":"17006","town"
:"Hartley Wespall"},{"town_id":"17007","town":"Hartley Wintney"},{"town_id":"27051","town":"New Hartley"
},{"town_id":"35891","town":"Stowe-by-Chartley"}]
Where am I going wrong? I would ideally like the select dropdown to have the select value = town_id and the select option to be the town name.
Thank You.
in your select2 configuration:
results: function (data) {
var res = [];
for(var i = 0 ; i < data.length; i++) {
res.push({id:data[i].town_id, text:data[i].town});
}
return {
results: res
}
},
becasue select2 wants the results as array of object with keys id and text.
Otherwise you could already returns a well formed object
[
{"id":"16994","text":"Hartle"},
{"id":"16995","text":"Hartlebury"},
{"id":"16996","text":"Hartlebury"},
{"id":"16997","text":"Hartlebury Common"}
]
then
results: function (data) {
return {
results: data
}
},
On your ajax call, try adding success. Something like this:
success: function( json ) {
$.each(items, function (i, item) {
$('#mySelect').append($('<option>', {
value: item.value,
text : item.text
}));
)};
}
After a few hours of deciphering tutorials, I finally got codeigniter and jquery autocomplete to work with each other...kind of.
Firebug is displaying the correct search terms back in JSON format, but the drop down box is not displaying any text. If there are 2 results, it displays 2 empty rows.
you can see it 'not working' here: http://rickymason.net/blurb/main/home
JS:
$(document).ready(function() {
$(function(){
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
response(data);
}
});
},
minLength: 2
});
});
});
Controller:
public function search()
{
$term = $this->input->post('term', TRUE);
$this->thread_model->autocomplete($term);
}
Model:
public function autocomplete($term)
{
$query = $this->db->query("SELECT tag
FROM filter_thread ft
INNER JOIN filter f
ON ft.filter_id = f.filter_id
WHERE f.tag LIKE '%".$term."%'
GROUP BY tag");
echo json_encode($query->result_array());
}
Hopefully its an easy fix!
Thanks
Changing your code to something like this would work(I have tested in your site)
$( "#filter" ).autocomplete({
source: function(request, response) {
$.ajax({
url: "http://rickymason.net/blurb/main/search/",
data: { term: $("#filter").val()},
dataType: "json",
type: "POST",
success: function(data){
var resp = $.map(data,function(obj){
return obj.tag;
});
response(resp);
}
});
},
minLength: 2
});
Copy and paste the above code block in your firebug console and then try the autocomplete. It will work. I tried in your site and it worked.
Secondly you dont need both $(document).ready(function() { and $(function(){ at the same time as they accomplish the same thing.
Check this section of jQuery UI autocomplete
Expected data format
The data from local data, a url or a callback can come in two variants:
An Array of Strings:
[ "Choice1", "Choice2" ]
An Array of Objects with
label and value properties: [ { label: "Choice1", value: "value1" },
... ]
Reference: $.map
Looking at this question on SO you need to setup your label and value fields on the response return. Try either arranging your PHP JSON output to match or map the return with something this the following (untested).
response( $.map(data, function(item){
return {
label: item.tag,
value: item.tag
};
})