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
});
Related
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 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.
Please help me to solve my problem.
$("#kategori_laporan").change(function() {
$("#loaderIcon").show();
$("#imgLoader").show();
var id = $(this).val();
$.ajax({
type: "POST",
dataType: "html",
url: "_views/getAjaxSubKategori.php",
data: "id="+id,
success: function(data) {
$(".select-skategori").select2({
ajax: {
url: "_views/getAjaxSubKategori.php",
dataType: 'json',
data: function(term, page) {
search = term.toUpperCase();
},
results: function(datas, page) {
return {
results: data
};
}
},
formatResult: function(option) {
return "<div>" +option._sub_kategori_laporan+ "</div>";
},
formatSelection: function(option) {
return option._sub_kategori_laporan;
}
});
}
});
});
Data not showing to subcategory select. Thanks before.!
Screenshot >> http://i.imgur.com/FlCeGpo.jpg
Why are you firing an ajax request before you initialize the select2 box?
I ask this, because your select2 box is requesting the search results via ajax as well. But maybe there is a reason. Please explain.
Then I can see in your screenshot, that your data returned from the json ajax request has not defined values id and text. If you are using other values ('_sub_kategori_id' and '_sub_kategori_laporan') in your json result, you have to tell the select2 box, what is your id and text field. I think you can do this with the processResults method as described here:
How to load JSON data to use it with select2 plugin
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 trying to load an array in my javascript. I need to send this array in some format to a PHP script that I'm going to call. In the example below, gSelectedMeds is my array. The value count will tell the PHP script how many meds items to expect to receive. I'm having trouble getting the data from the array into a format that I can send via the data option of $.ajax. Any help would be greatly appreciated!!
The part of the code below that is giving me grief at the moment is the data option:
$('#export').click(function() {
$.ajax({
url:'ajax-exportMeds.php',
data:
{"number":gSelectedMeds.length},
$.each(gSelectedMeds,
function(intIndex, objValue){
{"med"+intIndex:objValue},
}
),
type: "GET",
//dataType: "text",
success: function(data){
$('p#allMeds').text('');
$('a.bank').text('');
//clear array, bank and storedList divs
$(this).text('');
gSelectedMeds[] = '';
//$('ul#storedList').fadeOut('fast');
$('ul#storedList').text('');
return false;
},
}),
});
You should send the data as json. Then you can read it using json_decode() in php >= 5.2.0
I ended up stringing out the array and sending a count at the end of the url that I called:
$('#export').click(function() {
$.each(gSelectedMeds,
function(intIndex, objValue) {
i=intIndex + 1;
if(i>1) {string+='&';}
string+='med'+i+'="'+objValue+'"';
}
)
string += "&count="+i;
$.ajax({
url: 'ajax-exportMeds.php?'+string,
type: "GET",
dataType: "text",
success: function(data){
$('#dialog_layer').dialog({
autoOpen: true,
bgiframe: true,
modal: true,
closeOnEscape: true,
buttons: {
"OK": function() { $(this).dialog("close"); }
}
})
}
})
});