Select2 AJAX with JSON - javascript

I have been trying to populate my input with select2 using the JSON provided.
Here's the JSON:
{
"airports":
[
{
"id": "1",
"code": "AMQ",
"city": "Ambon",
"country": "Indonesia"
},
{
"id": "2",
"code": "BJW",
"city": "Bajawa",
"country": "Indonesia"
}
]
}
And the html code:
<input class="" type='hidden' value="192" data-init-text='Departing City' name='input' id='depart-airport' style="width: 300px"/>
And the js code:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
return { results: data};
}
}
});
});
There's no error in console, but whether I try to input them it's always saying that "searching failed" or there's not even anything. The data from json never showed.
Do you have anything to fix this around? Thanks's before :)

You have a minor error in your jQuery:
$(document).ready(function() {
$('#depart-airport').select2({
minimumInputLength: 1,
ajax: {
url: "http://localhost:4000/api/airports.json",
dataType: 'json',
results: function (data) {
// You had { results: data }, but your actual information is in data.airports
return { results: data.airports };
}
}
});
});

Related

Select2 and load JSON data

I have read a lot of questions here, but i'm not able to solve this
$('.titular').select2({
placeholder: 'Select',
width: '100%',
ajax: {
url: "/ajax/ajax.php",
data: function(params) {
var query = {
query: params.term
}
return query;
},
processResults: function(data) {
console.log(data);
return {
results: $.map(data, function (item) {
return {
id: item.id,
nome: item.nome
}
})
};
},
},
escapeMarkup: function (markup) { return markup; }
});
And my JSON:
[{"id":12,"nome":"Joe Bill"},{"id":13,"nome":"PJ"},{"id":14,"nome":"John"},{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}]
The results are not showing and developer console shows:
jQuery.Deferred exception: Cannot use 'in' operator to search for 'length' in [{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}] TypeError: Cannot use 'in' operator to search for 'length' in [{"id":16,"nome":"Acme"},{"id":17,"nome":"Acme2"},{"id":18,"nome":"Acme3"}]
I've tried to use the JSON viewed in oficial documentation, unsuccesfully...
I appreciate any help
The console error means that you are passing to the map an string so you need to parse your data as json before. I've done a little test and it is working like this:
processResults: function (data, params) {
data = JSON.parse('[{ "id": 12, "nome": "Joe Bill" }, { "id": 13, "nome": "PJ" }, { "id": 14, "nome": "John" }, { "id": 16, "nome": "Acme" }, { "id": 17, "nome": "Acme2" }, { "id": 18, "nome": "Acme3" }]');
var r = $.map(data, function (item) { return { id: item.id, text: item.nome }});
return { results: r };
}
Hope this helps.

How to call Angularjs controller function outside the controller in an Ajax call

Am trying to call Angularjs function outside the controller component like the below :
<script type="text/javascript">
function saveprof() {
$('.spinner').show();
$.ajax({
type: "POST",
url: "saveprof",
enctype: 'multipart/form-data',
async: true,
data: {
'rinput_Aj': JSON.stringify(angular.element(document.getElementById('rdExampleApp')).scope().$func()),
'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
},
success: function (data, textStatus, jqXHR) {
$('#message').html(data);
window.location.href = 'myprofile';
window.location('myprofile');
$('.spinner').fadeOut();
}
});
}
</script>
Here is the angularjs controller code :
<script>
var app = angular.module('rdExampleApp', ['ui.rdplot']);
app.controller('rdPlotCtrl', function ($scope) {
$scope.dataset = {
"d0": { "id": 0, "name": "Housing", "value": 18 },
"d1": { "id": 1, "name": "Travel", "value": 31.08 },
"d2": { "id": 2, "name": "Restaurant", "value": 64 },
"d3": { "id": 3, "name": "Bank", "value": 3 },
"d4": { "id": 4, "name": "Movies", "value": 10 }
};
$scope.func = function func() {
var jdata = $scope.dataset;
return jdata;
}
});
</script>
It throws an error
Uncaught TypeError: Cannot read property '$func' of undefined
EDIT:
After the suggestions, I converted my jquery ajax call to $http function in Angularjs.. But it does nothing.. No error in console :(
Here is how am invoking the $http service function
<body ng-controller="rdCtrl">
<a ng-click="saveprof()">Save</a>
<script>
var app = angular.module('rdExampleApp', ['ui.rdplot']);
app.controller('rdCtrl', function ($scope) {
$scope.dataset = {
"d0": { "id": 0, "name": "Housing", "value": 18 },
"d1": { "id": 1, "name": "Travel", "value": 31.08 },
"d2": { "id": 2, "name": "Restaurant", "value": 64 },
"d3": { "id": 3, "name": "Bank", "value": 3 },
"d4": { "id": 4, "name": "Movies", "value": 10 }
};
$scope.func = function func() {
var jdata = $scope.dataset;
return jdata;
}, function ($scope, $http) {
$scope.saveprof = function () {
//show spinner
$('.spinner').show();
$http.post('saveprof', {
data: { 'data': JSON.stringify($scope.dataset) }
})
.success(function (data) {
if (data == "null") {
//your code if return data empty
} else {
//your code if return data not empty
$('#message').html(data);
}
//hide spinner
$('.spinner').fadeOut();
})
.error(function (data, status, headers, config) {
console.log('error' + status);
//hide spinner in case of error
$('.spinner').fadeOut();
})
}
}
);
</script>
</body>
What am I missing?
in order to run XMLHttpRequest requests to the server you have many options in angularjs, you dont have to mess with simple javascript and call angular scope to get variables and functions.
you can do that either with $http or with services(leave it for now).
i am going to show how you can make the request with $http in native angular.
first of all you have to import the $http module on the declaration of your controller, like this :
var app = angular.module('rdExampleApp', ['ui.rdplot']);
app.controller('rdPlotCtrl', function ($scope,$http) {...});
into you controller you create the json object as you do it and then do the request like this:
//show spinner
$('.spinner').show();
$http.post('dal/addEventHalls.php', {
data: {'data': $scope.datase}
})
.success(function (data) {
if (data == "null") {
//your code if return data empty
} else {
//your code if return data not empty
}
//hide spinner
$('.spinner').fadeOut();
})
.error(function (data, status, headers, config) {
console.log('error' + status);
//hide spinner in case of error
$('.spinner').fadeOut();
})
as you can see we dont use url parameter but we pass the url directly into post() function. the data parameter is there to put whatever data you would like to send to the server.
hope helps good luck.
UPDATE
personally i dont stringify the data parameters.i pass them like json object
into php file , in order to get the data , try this:
$params = json_decode(file_get_contents('php://input'), true); //read values from angular factory-service

Create datatable in js via json data in a variable?

now I encounter a problem. I want to use ajax to show a datatable via using data coming from sql server database. Current state is I have used ajax to call a Handler.ashx to connect sql server and convert the data to json (using newtonsoft.json). In ajax, all json data has been recevied from Handler.ashx and stored in a variable "msg" which could be successfully showed on page. I want to put this "msg" into a datatable but failed all the time. I tried almost all methods online to set the datatable but still give different errors. I want to create a datatable in js and fill in my json data. But the result is either null or no data available in table.
Here is the codes and json data looks like.
js:
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
//contentType: "application/json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
cache: false,
success: function (msg) {
//for (var i in msg) {
// $("#eventGrid").append(msg[i]);
//}
//var jsonStr = JSON.stringify(msg);
document.getElementById("result").innerHTML = msg;
$('#eventtable').dataTable({
//"paging": false,
//"searching": false,
//"retrieve": true,
//"bProcessing": true,
//"data": msg.data,
//"datatype": "JSON",
//"ajax": "HandlerAll.ashx",
//"aaData": JSON.parse(msg),
//"ajax":
//"dataSrc":virtualTable
//"aoColumns": [
// { "mData": "ID" },
// { "mData": "FESTIVAL" },
// { "mData": "SUBURB" },
// { "mData": "POSTCODE" },
// { "mData": "WEBSITE" },
// { "mData": "DESCRIPTION" }
// ]
});
},
error: function (data) {
alert("Server error.");
}
})
});
});
json data (the size depends on the search condition, the table columns should have "ID","Festival" and so on, but no "virtualTable"):
{ "virtualTable": [ { "ID": "1", "FESTIVAL": "Antipodes Festival", "SUBURB": "Lonsdale Street, Melbourne", "POSTCODE": "3000", "WEBSITE": "http://www.antipodesfestival.com.au/", "DESCRIPTION": "The greek precinct in melbourne cbd will transform into a huge, free street festival with the hosting of the antipodes lonsdale street festival which will hold sway from 14 february 2015 to 15 february 2015." }, { "ID": "5", "FESTIVAL": "Boite Singers Festival", "SUBURB": "Victoria", "POSTCODE": "3000", "WEBSITE": "http://boite.com.au/index.php", "DESCRIPTION": "The boite singers festival brings you four days of vocal inspiration and sheer fun on the second weekend of january each year." } ] }
Since you get a JSON as reponse, I would try to convert it to JSON object, take the virtualTable part that it is a set of records in JSON and convert it to an array to add it to my table.
$(document).ready(function () {
$("#eventsButton").click(function () {
$.ajax({
type: "POST",
url: "../Handler.ashx",
// dataType: "json",
data: { postcode: $("#eventsPostcodeTextbox").val() },
success: function (msg) {
var jdata = $.parseJSON(msg);
jdata = jdata.virtualTable;
if (jdata.length != 0) {
var array_data = [];
var temp_array = [];
$(jdata).each(function(key, value) {
temp_array = [];
temp_array = [value.ID,
value.FESTIVAL,
value.SUBURB,
value.POSTCODE,
value.WEBSITE,
value.DESCRIPTION
];
array_data[array_data.length] = temp_array;
});
$('#eventtable').dataTable().fnAddData(array_data);
$('#eventtable').dataTable().fnDraw();
},
error: function (data) {
alert("Server error");
}
SOLUTION
Use the code below to initialize the table:
$('#eventtable').dataTable({
data: msg.virtualTable,
columns: [
{ data: "ID" },
{ data: "FESTIVAL" },
{ data: "SUBURB" },
{ data: "POSTCODE" },
{ data: "WEBSITE" },
{ data: "DESCRIPTION" }
]
});
DEMO
See this jsFiddle for code and demonstration.

loading data in datatable on onchange event

I want to implement function in which data will be loaded into datatable after onChange event. So for that I am trying to implement code as below.
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
Which is creating my datatable layout and I am calling below function on dropdown change event is :
function loadFeedback(){
viewdatatabJS = $('#dataTablesFeedback').dataTable({
"processing" : true,
"retrieve" : true,
"ajax" : "/nhp/rest/feedback/viewFeedback",
"fnServerParams": function ( aoData ) {
aoData.push( { "name": "userName", "value":employeeId } ,
{ "name": "resourceId", "value":mentorDataJson[$('#dropDownId').val()].resourceId });
},
});
}
Where I am passing some parameter in aoData.push but my URL is not getting called.
I Solved the issue by simply implementing datatable properties. i wrote my code of datatable
var viewdatatab = $('#dataTablesFeedback').dataTable({
"columns": [
{ "data": "resourceId" },
{ "data": "feedbackRecommendation" },
{ "data": "technicalSkillGaps" },
{ "data": "technicalAvgSkills" },
{ "data": "feedbackType" },
{ "data": "feedbackId" },
{ "data": "isNew" },
]
});
in jsp document.ready(function()) and then on my request call of drop down change event i wrote below code on my javascript function.
$.ajax({
url : "",
type: 'GET',
contentType: "application/json",
data: {
'userName': value,
'resourceId' : value,
},
success: function(data) {
var table = $('#dataTablesFeedback').DataTable();
table.clear();
table.rows.add(data.data);
table.draw();
});
this way i first clear my datatable and then redraw it using my json which i got from my ajax call.
Thanks

WoW Armory APi - Can't get Title

Hello I'm trying to pull my characters title from the Warcraft Armory but I don't get any returned results. My code is as follows with my character name being replaced with my actual character name .
HTML
<li>Title Prefix: <span id="title">Test</span>
Javascript
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
});
}
);
function GoGet(data) {
$("#title").html(data.titles.name)
;}
The api documentation shows the json items for "titles" as follows:
{
"achievementPoints": 675,
"battlegroup": "Test Battlegroup",
"calcClass": "f",
"class": 10,
"gender": 1,
"lastModified": 1348187981118,
"level": 90,
"name": "Peratryn",
"race": 25,
"realm": "Test Realm",
"thumbnail": "test-realm/1/1-avatar.jpg",
"titles": [
{
"id": 285,
"name": "%s, Savior of Azeroth",
"selected": true
}
]
}
Where am I going wrong?
Not being a WOW player myself, I'll hazard one guess:
$(window).load(function getSite(){
$.ajax({
url: "http://eu.battle.net/api/wow/character/server/character?fields=titles&jsonp=GoGet",
type: 'GET',
dataType: 'jsonp',
success: UpdateTitle
});
}
);
function UpdateTitle(response) {
if (response.titles) {
for (var i = 0; i < response.titles.length; i++) {
if (response.titles[i].selected === true) {
$("#title").html(response.titles[i].name);
break;
}
}
}
}
What this is doing is calling UpdateTitle after a successful XHR response from your provided URL. This function will loop through each title and update your #title element with the FIRST selected: true title found in the json response.

Categories

Resources