I have an API that is called by Select2 (v4.0.5) however the debug message in the console says:
Select2: The AJAX results did not return an array in the results key of the response.
When I review the documentation at Select2's documentation site I seem to be following it correctly. This is the javascript I use on the webpage:
$('#account_id').select2({
debug: true,
minimumInputLength: 3,
dataType: 'json',
ajax: {
url: '/api/account-query',
data: function (params) {
var query = {
search: params.term,
v: "new"
}
return query;
},
}
});
This is the response from the API (sensitive bits redacted):
{
"results": [{
"id": "redacted-1",
"text": "text redacted 1"
},{
"id": "redacted-2",
"text": "text redacted 2"
},{
"id": "redacted-3",
"text": "text redacted 3"
},{
"id": "redacted-4",
"text": "text redacted 4"
},{
"id": "redacted-5",
"text": "text redacted 5"
}]
}
If I take the select2 code and supply it with the static json response (without results prepended, just the array) it works just fine.
What am I missing?
Thanks!
You have to provide the processResults callback function so Select2 able to render result in proper way.
I have created a jsfiddle (https://jsfiddle.net/shcavbng/) demo that doing the same.
$('#account_id').select2({
debug: true,
minimumInputLength: 3,
dataType: 'json',
ajax: {
url: 'https://reqres.in/api/users',
data: function (params) {
console.log('params =>' , params);
var query = {
search: params.term,
v: "new"
}
return query;
},
processResults: function (data) {
console.log('results =>' , data);
data = data.data.reduce(function(o,i){o.push({id:i.id,text:i.first_name});return o;},[]);
console.log('results =>' , data);
return {
results: data
};
}
}
});
I figured it out, and as expected I was overlooking a simple aspect:
Content-Type header needed to be application/json vs text/html
Related
I'm calling sub domain controller method from main domain using ajax call as follows
$.ajax({
type: "POST",
url: "https://demo.trufin.in/getBorrowerType",
cache: false,
dataType: "json",
success: function(response) {
//success part
},
error:function(error){
//error part
}
});
I get response as 200 (Status ok) as well as I get json data as follows
[{
"borrowerTypeName": "Co-operative Member",
"addedDate": "2016-10-04",
"borrowerTypeId": 1,
"addedBy": "23646",
"isActive": 1
}, {
"borrowerTypeName": "Bank Account Holder",
"addedDate": "2016-10-04",
"borrowerTypeId": 2,
"addedBy": "23646",
"isActive": 1
}, {
"borrowerTypeName": "Others",
"addedDate": "2016-10-04",
"borrowerTypeId": 3,
"addedBy": "23646",
"isActive": 1
}]
But problem is ajax returns to error!!
Tried with all possible solutions like
dataType:jsonp
cross origin
But didn't work.
For consistency's sake, try wrapping your numbers also in quotation marks.
I am using the newest Select2 4.0.6-rc.1 and I am making an AJAX search, I am getting results back but for some reason they don't show up as an option on the SELECT element. Maybe I am missing some basic setup but I have been reading the docs and I can't find anything helpful. Here is what I have:
<select class="form-control" id="query"></select>
$(function() {
var $query = $("#query");
$query.select2({
width: 550,
placeholder: 'Search for a form ...',
minimumInputLength: 3,
ajax: {
url: '/ajax/forms/ajax_search_by_name',
data: function (params) {
return {
q: params.term
};
},
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data.items
};
}
}
});
});
The result from the backend looks like:
{
"results": [
{
"id": 1247,
"name": "amerita_infusion_services_colorado_synagis_referral_form"
},
{
"id": 3471,
"name": "medicaid_colorado_viekira"
}
]
}
Which I think is the right way to return them. I have setup a Fiddle - which BTW I couldn't make it to work with the /echo/json request - so you can play with it a little bit.
What I am missing here?
I have data in JSON created by Django serialization.
I use the example:
Select2 Loading remote data but still I getting information in a field that nothing found.
What should change to select2 work with data generated by Django?
JSON Data:
[{
"fields": {
"sku": "8"
},
"model": "catalog.product",
"pk": 8
},{
"fields": {
"sku": "9"
},
"model": "catalog.product",
"pk": 9
}]
Html:
<select class="js-data-example-ajax"><option value="3620194" selected="selected">select2/select2</option></select>
JavaScript:
$('.js-data-example-ajax').select2({
ajax: {
url: "{% url 'catalog.views.product_sku_json' %}",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term, // search term
page: params.page
};
},
processResults: function (data, params) {
// 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, except to indicate that infinite
// scrolling can be used
params.page = params.page || 1;
return {
results: data.items,
pagination: {
more: (params.page * 30) < data.total_count
}
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 1,
});
Answer by kevin-brown on github:
You are going to need to re-map your results to have id and text keys.
https://select2.github.io/announcements-4.0.html#changed-id
And it works thanks Kevin!
Apologies in advance - I am new to this and so other answers have not been able to help me.
I have used AJAX to send data to a PHP script (part of a 3rd party API). The PHP script returns the results as JSON, but I have no idea how to format these on my HTML page.
Ultimately, I would like to save the JSON results as an array and then use JS/Jquery to format them on the page.
I am not sure how to modify the PHP and AJAX scripts to achieve this. Can anyone point me in the right direction?
My AJAX:
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {toPostcode: toPostcodeValue, parcelLengthInCMs: parcelLengthInCMsValue, parcelHeighthInCMs: parcelHeighthInCMsValue, parcelWidthInCMs: parcelWidthInCMsValue, parcelWeightInKGs: parcelWeightInKGsValue},
success: function(data) {
<!--NOT SURE WHAT TO PUT HERE-->
}
})
PHP (after the calculator does its thing - not sure if it needs to be changed):
$serviceTypesJSON = json_decode($rawBody);
echo json_encode($serviceTypesJSON);
The expected JSON results should look like:
{
"services": {
"service" : [
{
"code": "AUS_PARCEL_REGULAR",
"name": "Parcel Post (your own packaging)",
"speed": 2,
"price": 6.95,
"max_extra_cover": 5000,
"extra_cover_rule": "100,1.5,1.5",
"icon_url": "http://test-static.npe.auspost.com.au/api/images/pac/regular_post_box.png",
"description": "Based on the size and weight you've entered",
"details": "Check our ",
"delivery_time": "Delivered in up to 3 business days",
"ui_display_order": 1,
"options": {
"option": [
{
"code": "AUS_SERVICE_OPTION_STANDARD",
"name": "Standard Service",
"price": "0.00",
"price_type": "static",
"option_type": "optional",
"ui_display_order": 1
},
{
"code": "AUS_SERVICE_OPTION_SIGNATURE_ON_DELIVERY",
"name": "Signature on Delivery",
"price": 2.95,
"price_type": "static",
"option_type": "optional",
"tooltip": "Signature on Delivery provides you with the peace of mind that your item has been delivered and signed for.",
"ui_display_order": 2,
"suboptions": {
"option": {
"code": "AUS_SERVICE_OPTION_EXTRA_COVER",
"name": "Extra Cover",
"option_type": "optional",
"price_type": "dynamic",
"tooltip": "Extra Cover provides cover for loss, damage or theft of your item and will fully compensate you to the value specified for your item.",
"ui_display_order": 1
}
}
}
]
}
},
You can do two things, if the return data is JSON use dataType: "json" in the AJAX call.
Edit 1
If you are using dataType: "json". Which is more preferred if you are sure the data return is JSON string. data variable in the success will directly give you the JSON object. I think you can access it like data['services'].
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services;
}
Or you can just get the data then use jQuery.parseJSON() to parse the data string into JSON object.
$.ajax({
type: 'POST',
url: 'calculator.php',
data: {
toPostcode: toPostcodeValue,
parcelLengthInCMs: parcelLengthInCMsValue,
parcelHeighthInCMs: parcelHeighthInCMsValue,
parcelWidthInCMs: parcelWidthInCMsValue,
parcelWeightInKGs: parcelWeightInKGsValue
},
success: function (data) {
jsonObj = $.parseJSON(data);
//this gives you the inner onject of the return data
servicesObj = jsonObj.services; //or jsonObj["services"]
}
})
Your success function will never be called if you are using
echo json_encode(); in your php script.
You should add dataType:'json' after type:'POST' and then your success function will get called and will get the result returned by server in data
I have a YQL output JSON string at this URL: YQL JSON
I found some other
I am trying to understand why I cannot get certain items out of the JSON return. For example, using jQuery, if I want the first DIVs H1 I use:
$.ajax({
url:"http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.missoulaavalanche.org%2Fcurrent-advisory%2F%22%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22content%22%5D%2Fdiv%5B1%5D'&format=json",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc'
});
function cbfunc(data){
var id = data.query.results.div;
$('#table').append('<li>'+id.h1+'</li>');
$('#table').listview('refresh');
}
I have tried to get some info, say the img alt or img src, from the second div... div1 like so:
function cbfunc(data){
var id = data.query.results.div[1];
$('#table').append('<li>'+id.img.alt+'</li>');
$('#table').listview('refresh');
}
I keep getting Undefined or no results... What I am missing or not understanding about getting results from the yql JSON list?
EDIT: I read a post on the YQL Blog about Cache busting... So I am using their suggestion there.
EDIT 2: here is the JSON from the yql. I would like to get div img src for example, but am not getting a return or I get an object. I think it would be data.query.results.div1.img.src
I get data.query.results.div.h1 no problem:
cbfunc({
"query": {
"count": 1,
"created": "2012-03-28T15:36:28Z",
"lang": "en-US",
"results": {
"div": {
"id": "content",
"div": [
{
"class": "post-2491 post type-post status-publish format-standard hentry category-advisories",
"id": "post-2491",
"h1": "March 26, 2012 Avalanche Advisory",
"p": {
"class": "postmetadata alt",
"small": {
"br": [
null,
null
],
"a": {
"href": "http://www.missoulaavalanche.org/category/advisories/",
"rel": "category tag",
"title": "View all posts in Advisories",
"content": "Advisories"
},
"content": "This entry was posted on Monday, March 26th, 2012 at 6:55 am\n Categories: \n"
}
},
"div": [
{
"id": "danger_rating",
"a": {
"href": "http://www.missoulaavalanche.org/wp-content/themes/missoula-avalanche/images/ratings/avalanche_danger_scale.jpg",
"img": {
"alt": "Current Danger Rating is MODERATE",
"src": "http://www.missoulaavalanche.org/wp-content/themes/missoula-avalanche/images/ratings/moderate.gif"
}
}
},
{
The jsonp function option is just define the function name server uses for the wrapper for jsonp.
To access your data you need to do it in success callback of $.ajax. Your code above is missing the $ before .ajax
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.missoulaavalanche.org%2Fcurrent-advisory%2F%22%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22content%22%5D%2Fdiv%5B1%5D'&format=json",
dataType: 'jsonp',
jsonp: 'callback',
jsonpCallback: 'cbfunc',
success: function(data) {
var results=data.query.results;
/* work with results object here*/
}
});
It's easier than you think if you use jQuery.getJSON.
Try this:
$.getJSON("http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20html%20where%20url%3D%22http%3A%2F%2Fwww.missoulaavalanche.org%2Fcurrent-advisory%2F%22%20and%20xpath%3D'%2F%2Fdiv%5B%40id%3D%22content%22%5D%2Fdiv%5B1%5D'&format=json",
function(data) {
var id = data.query.results.div;
$('#table').append('<li>'+id.h1+'</li>');
$('#table').listview('refresh');
}
);