jQuery Select2 not displaying Data - javascript

I am stuck at problem where i believe i am getting the response in correct format but i am not able to display the data returned from the server. Intelligent Minds! I need your help.
Below is my HTML code:
<div class="form-group">
<select id="owner" class="dropDowns">
<option value="00000" selected="selected">Select Owner</option>
</select>
</div>
JQuery Code:
This function is getting called with no problems and a result is also returned from the server but some how i am not able to format that result and display it to the user. I am not sure what i am doing wrong and this has been bugging me for quiet some time now.
$("#owner").select2({
minimumInputLength: 3,
ajax: {
url: "http://localhost:8080/iam/aexp/rest/ePAAS/getOwner",
dataType: "jsonp",
headers: {
"Authorization": "Basic " + btoa('spadmin' + ":" + 'admin')
},
type: 'GET',
delay: 250,
data: function (params) {
return {
adsId: params.term, // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
formatResult: function (data) {
return "<div>" + data.id + "</div>";
},
formatSelection: function (data) {
return data.id;
}
});
And here is the response I am getting from the server:
[{"id":0,"text":"rgadke"}]
Thanks!

I found the issue. I was not returning the result in the correct JSON format

Related

DOM updated , however changes not visible in browser

I'm trying to populate html select with an ajax call using jquery. I can see that the dom is getting updated with data from database , however the updated options are not visible on brower.
Here is the static html:
<td>
<div>
<select data-placeholder="-Role-" multiple class="chosen-select"
style="width:170px;">
<option value="TEST_ROLE1">TEST_ROLE1</option>
<option value="TEST_ROLE2">TEST_ROLE2</option>
</select>
<span userId="grouproleError" class="alert alert-danger col-sm-4"
style="display:none"></span>
</div>
</td>
Following is the script code :
$(document).ready(function () {
$('.chosen-select').chosen({}).change(function (obj, result) {
console.debug("changed: %o", arguments);
console.log("selected: " + result.selected);
});
/**
* Get All roles
**/
console.log('Getting all roles..' + new Date().toLocaleString());
$.ajax({
url: "http://localhost:8081/admin/roles/getallroles",
context: document.body,
dataType: "json",
type: "GET",
contentType: "application/json; charset=utf-8",
success: function (data) {
var list = $(".chosen-select");
$.each(data, function (index, item) {
list.append(new Option(item.rolesShortName, item.rolesShortName));
});
console.log('Roles fetched:' + JSON.stringify(data));
},
error: function () {
window.location.replace("http://localhost:8081");
}
});
$('form').submit(function (event) {
register(event);
});
});
$(document).ajaxStop(function () {
$(".log").text("Triggered ajaxStop handler.");
});
}
You can see that the static options are the only options getting displayed.
Options retrieved from the database are updated in the DOM however they are not getting displayed. What do you think I'm doing wrong?
As per the documentation $('.chosen-select').trigger('chosen:updated') was required after the DOM was modified.

Data passing error from javascript to controller

I'm working on ASP.NET MVC project , I want to get location dropdown selected value and according to that i need to load values to City dropdown , i implemented following code and location dropdown onselect event call the javascript function and javascript function call the controller method but when executing controller method locationId is null ,and i debug javascript and locationID is there till the this line data: JSON.stringify({ locationId: +locationId }), after that javascript returns error.but controller method get hit but locationId null
code for dropddowns
<div class="row">
<div class="col-sm-4">
#Localizer["Locations"]
<select id="locationDropDown" class="selectpicker form-control" asp-for="selectedLocation" onchange="getCityList()">
<option value="0"><None></option>
#foreach (var item in Model.LocationList)
{
<option value="#item.Id">#item.Name</option>
}
</select>
</div>
</div>
<div class="row">
<div class="col-sm-4">
#Localizer["KioskGroup"]
<select id="cityDropDown" class="selectpicker form-control">
<option>---Select City---</option>
</select>
</div>
</div>
Javascript code
function getCityList()
{
debugger;
var locationId = $("#locationDropDown").val();
console.log(locationId)
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
datatype: 'application/json',
contentType: 'application/json',
data: JSON.stringify({ locationId: +locationId }),
success: function (result) {
$("#cityDropDown").html("");
$("#cityDropDown").append
($('<option></option>').val(null).html("---Select City---"));
$.each($.parseJSON(result), function (i, zone)
{ $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })
},
error: function(){alert("Whooaaa! Something went wrong..")},
});
controller method
public ActionResult GetZoneListBYlocationID(string locationID)
{
List<Zone> lstZone = new List<Zone>();
long locationId = long.Parse(locationID);
var zones = _zoneRepository.GetZonesByLocationId(locationId);
return Json(JsonConvert.SerializeObject(zones));
}
Your current code is sending the json string {"locationId":101} in the request body because you specified the contentType as application/json. This is useful when you want to send an object with multiple properties and your action method parameter is a DTO/POCO class type. Model binder will be reading from the request body and map it to the parameter.
In your case, all you are sending is a single value. So do not send the JSON string. simply create a js object and use that as the data attribute value. Also remove the contentType: application/json as we are not sending a complex js object as json string.
Also application/json is not a valid option for the dataType property. You may use json. But jQuery is smart enough to guess the value needed here from the response headers coming back from server. So you may remove it.
function getCityList() {
var locationId = $("#locationDropDown").val();
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
data: { locationID: locationId },
success: function (result) {
console.log(result);
// populate dropdown
},
error: function () { alert("Whooaaa! Something went wrong..") },
});
}
Now this data will be send in Form Data as locationID=101 with Content-Type header value as application/x-www-form-urlencoded and will be properly mapped to your action method parameter.
You should use the correct types. In your action method, you are using string as your parameter and later trying to convert it to long. Why not use long as the parameter type ? Also if zones variable is a list of Zone object, you can pass that directly to the Json method. No need to create a string version in between.
public ActionResult GetZoneListBYlocationID(long locationId)
{
var zones = _zoneRepository.GetZonesByLocationId(locationId);
return Json(zones);
}
Why you are stringify the data.Below one should work without stringify
data: { locationId: +locationId },
I was facing the same problem. and after that, I have tried below solution.
Hope it will help you.
ajax call is as follows:
$.ajax({
type: 'POST',
url: "/Account/GetCities",
dataType: 'json',
data: { id: $("#StateID").val() },
success: function (states) {
$.each(states, function (i, state) {
$("#CityID").append('<option value="' + state.Value + '">' + state.Text + '</option>');
});
},
error: function (ex) {
alert('Failed to retrieve cities.' + ex);
}
});
The controller code is as follows:
public List<CityModel> GetCities(int id)
{
//your code
}
You can do in your application like this:
function getCityList()
{
var locationId = $("#locationDropDown").val();
console.log(locationId)
$.ajax({
url: '/Kiosk/GetZoneListBYlocationID',
type: 'POST',
dataType: 'json',
data: { locationId: locationId },
success: function (result) {
$("#cityDropDown").html("");
$("#cityDropDown").append
($('<option></option>').val(null).html("---Select City---"));
$.each($.parseJSON(result), function (i, zone)
{ $("#cityDropDown").append($('<option></option>').val(zone.Id).html(zone.Name)) })
},
error: function(){alert("Whooaaa! Something went wrong..")},
});
}
And your controller will be same as you have done.

Select2 TypeError: b is undefined

I'm using select2 to show ajax results in a dropdown but when I append data to select2 its showing error
TypeError: b is undefined
JS Code
var baseurl = $("#baseurl").val();
$(".myselect").select2({
placeholder: "Select a inspector",
allowClear: true,
ajax: {
url: baseurl + '/admin/getdata',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
results: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.firstname
});
});
return {
results: myResults
};
}
}
});
term.term contains the value of input text in dropdown search box.
HTML
<select class="myselect" style="width: 50% !important">
<option></option>
<option value="AL">Alabama</option>
<option value="WY">Wyoming</option>
<option value="KY">Kentucky</option>
</select>
JSON RESPONSE
[{"id":9858,"firstname":"Testing3","status":2,"state":"VA","phone":""},{"id":9857,"firstname":"Testing2","status":2,"state":"VA","phone":""},{"id":9856,"firstname":" david polosky ","status":3,"state":"FL","phone":"(000)000-4141"}]
SELECT2 CDN LINKS
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
PHP SERVERSIDE CODE (LARAVEL)
$searchtext = $request->get('term');
$data = Inspector::latest('id')
->select('id', 'firstname', 'status', 'state', 'phone')
->where('firstname', 'LIKE', '%' . $searchtext . '%')
->get()->toArray();
echo json_encode($data);
Any help is appreciated.
In your ajax configuration you use results you should use processResults
Try this
var baseurl = $("#baseurl").val();
$(".myselect").select2({
placeholder: "Select a inspector",
allowClear: true,
ajax: {
url: baseurl + '/admin/getdata',
dataType: 'json',
type: "GET",
quietMillis: 50,
data: function (term) {
return {
term: term.term
};
},
processResults: function (data) {
var myResults = [];
$.each(data, function (index, item) {
myResults.push({
'id': item.id,
'text': item.firstname
});
});
return {
results: myResults
};
}
}
});
Aamir#, sometimes errors are misleading. If you see from your code, it doesn't have a reference to b at all. I believe that must be an error that is being thrown from a method outside of your code, due to an error in your code.
You might have to set a break point by clicking on the line number on browser console and then check the call stack to find the error in the code.

select2 version 4 ajax data : results not appearing in control

Since I have switched to version 4 of the select2 plugin, my ajax calls do not work anymore.
I get a response in the form of an array which prints ok in the console but the results don't show in the select2 control.
http response :
{"results":{"id":"ok","term":"ok","description":"ok"}}
My code :
$(function(){
$('#appbundle_marketplace_product_ingredient_barcode').select2({
minimumInputLength: 3,
ajax:
{
delay: 250,
url: "{{ path('search_barcode') }}",
dataType: 'json',
debug: true,
data: function (params) {
// console.log(params.term);
return {barcode: params.term};},
processResults: function (data) {
console.log(data);
return data;
}
}
});
});
the data printed in the console is the following object :
Object {results: Object}
results: Object
description: "ok"
id: "ok"
term: "ok"
__proto__: Object
__proto__: Object
How can I have the select2 display a result in the dropdown, then click the result to have it selected ?
Thanks a lot,
Great question, same issue I ran into.
I had a similar issue, working in Wordpress. I had to update my php to return this:
// This prepared SQL query returns objects, so I thought I was fine
$partList = $wpdb->get_results( $sql );
// echo json_encode( $partList ); <- worked, but not quite right...
// Select2 wanted an array of items, so I added this
$jsonItems = array("items"=>$partList);
echo json_encode( $jsonItems );
In my JS I have this...
function formatPartSelection(ajaxData){
return ajaxData.commonName || ajaxData.text;
}
function formatAjaxResponse (ajaxData){
if(ajaxData.loading) return ajaxData.text;
var markup = '<div class="clearfix select2-result-selectable" style="border-bottom:solid; border-bottom-color: #D3D3D3">' +
'<div class="col-sm-10">' +
'<div class="clearfix">' +
'<div class="col-sm-10"><span style="font-weight: bold;">' + ajaxData.fieldOne + ' | ' + ajaxData.text + '</span></div>' +
'</div>';
if (ajaxData.description) {
markup += '<div class="col-sm-10">' +
'<div class="clearfix">' +
'<div><i>' + ajaxData.description + '</i></div>';
}
markup += '</div><br/></div>';
return markup;
}
$.fn.select2.amd.require(
["select2/core", "select2/utils", "select2/compat/matcher"],
function (Select2, Utils, oldMatcher) {
});
$('.myClass').select2({
placeholder: "Select part(s)...",
minimumInputLength: 3,
multiple: true,
ajax: {
url: url_to_your_php,
delay: 250,
type: "POST",
dataType: 'json',
data: function (params) {
var queryParameters = {
action: 'my_enqued_wp_ajax',
searchStringValue: params.term
}
return queryParameters;
},
processResults: function (data) {
console.log(data);
return {
results: data.items
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; },
templateResult: formatAjaxResponse,
templateSelection: formatPartSelection
});
The above code allowed me to get the list of items to select from working, but I couldn't actually click any of them. Many hours later, I found this answer which helped me to actually be able to select one of the values in my Select2 dropdown list:
https://stackoverflow.com/a/29082217/4266699
*Note, I had the luxury of creating a column in my DB called ID, so I was able to fix this on the backend.
Hope this helps!

Select2 not getting data via AJAX

I have the following code which should be getting data via AJAX using Select2
$('#Organisation').select2({
ajax: {
url: AppURL + 'Organisations/Manage/SearchByName/',
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
return {
results: data
};
}
}
});
If I look at the request using Web Inspector when searching 'O' I get:
[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1}]
Any ideas what I'm doing wrong? I'd presume something incorrect in the results function.
The error I get is: Uncaught TypeError: Cannot call method 'toUpperCase' of undefined
Try
$('#Organisation').select2({
ajax: {
url: 'data.json',
dataType: 'json',
quietMillis: 100,
data: function (term) {
return {
term: term
};
},
results: function (data) {
var results = [];
$.each(data, function(index, item){
results.push({
id: item.ID,
text: item.label
});
});
return {
results: results
};
}
}
});
Demo: Plunker
Other than above solution you can do one thing, instead of returning following json
[{"label":"Organisation 1","ID":2},{"label":"Organisation 2","ID":1}]
return this
[{"text":"Organisation 1","id":2},{"text":"Organisation 2","id":1}]
faced the same problem and figured this out after looking at few solutions proposed by other.

Categories

Resources