I try to apply the example of Select2 in loading remote data, but do not quite understand how it should be the json format.
Using this example:
$(".js-data-example-ajax").select2({
ajax: {
url: "http://localhost:8081/pruebas/select2/examples/jsondata.php",
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: 1,
});
My json has the following format:
[{"id":0,"text":"Wilmer Hilaquita"},{"id":1,"text":"Juana de Arco"}]
When you start the search, ajax sent me this message:
GET http://localhost:8081/pruebas/select2/examples/jsondata.php?q=Wil
Json not find anything, let me know if sending the json should receive it as a parameter $ _GET and work in the json with that parameter, considering that my data are higher than 60000 records
If you don't need pagination you can simplify processResults function and have something like:
processResults: function (data, params) {
return {
results: data
};
}
(this assuming that data is an array of objects having id and text properties). If this is not the case, inside the same function you need to process your response in order to get the same type of array.
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
});
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]}
I am trying to use select2 pulling data using ajax from php back end. I could not figure out the documentation as much as I would like to. I think i probably missed some taken for granted stuffs. Please can you help with a simple example. I started or like this...
html
<select id="select_proj" style="width:10em">
<option value="" selected="selected">Search</option>
</select>
js
$('select').select2();
$("#select_proj").select2({
ajax: {
url: '../app/select_prj.php',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
select_proj: term, // search term
page: 10
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
In php
$data_wildcardsearch = $_POST['term'];
is throwing error
[Notice: Undefined index: term in b>-----/app/select_prj.php on line 18]
Could you please help? Can you please share a sample code as well?
In data() function you must pass 'term' as a key instead of select_proj.
$('select').select2();
$("#select_proj").select2({
ajax: {
url: '../app/select_prj.php',
dataType: 'json',
delay: 250,
data: function (term, page) {
return {
term: term, // search term
page: 10
};
},
processResults: function (data, page) {
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
Then you can get it by:
$data_wildcardsearch = $_POST['term'];
You have post term with key => 'select_proj'.
Change code as below,
$data_wildcardsearch = $_POST['select_proj'];
OR
data: {term: term, page: 10},
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
}));
)};
}
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"
}
});