I have created a code which fetches data using the Ajax Call and populate it to the data table UI.
My code is as below:
jQuery.ajax(
{
url: _spPageContextInfo.webAbsoluteUrl + "/_api/Web/Lists/GetByTitle('Events')/items?$select=Title,Session_x0020_Room,Session_x0020_Date,StartTime,EndTime,Duties,OnsiteContactEmail",
type: "GET",
headers: { "Accept": "application/json;odata=verbose" },
dataType: "json",
success: function (data, textStatus, xhr) {
if (data.d.results.length > 0) {
var resColl = data.d.results;
var strData= new Array();
for(var i=0; i < resColl.length; i++){
var arr = new Array();
arr.push(resColl[i].Title);
arr.push(resColl[i].Session_x0020_Room);
strData[i] = JSON.stringify(arr);
}
$('#example').DataTable({
data:strData,
columns: [
{ title: "Event" },
{ title: "Room" }
]
});
}
},
error: function (data, textStatus, xhr) {
console.error("Error while getting the data from Events list");
}
});
In strData object I am getting this value: "["Asian Women in Computing","Room 1"]"
But in the table of HTML I am not getting proper output.
What am I missing?
I'm assuming that DataTable expects an array of arrays that exists of strings. You have an array of JSON strings because you convert the array arr to a JSON string and push it to strData, which DataTable will later use.
var resColl = data.d.results;
var strData= new Array();
for(var i=0; i < resColl.length; i++){
var arr = new Array();
arr.push(resColl[i].Title);
arr.push(resColl[i].Session_x0020_Room);
strData[i] = arr;
}
Don't convert arr to a JSON string and it should print fine.
Related
i have a function . here i am passing an array applicationTabId = {"twitter": "15", "dropbox": "14"}; "}; I have an ajax success function .In this the variable appName name holds the key names as twitter , dropbox etc. I got this from database as ajax response. i want to find the value associated with this from the array. variable appName holding the key names and iam getting it from database as ajax response. i need to check the corresponding value of this name from array.
function getapplicationlogouturl(applicationTabId) {
chrome.storage.sync.get("endpoint", function (obj) {
FetchLogoutUrl = {
"applicationName": applicationTabId,
"sdcode": sdcode,
"type": "Chrome Fetch Application Logout Url"
};
$.ajax({
type: "POST",
url: obj.endpoint,
dataType: "json",
data: JSON.stringify(FetchLogoutUrl),
context: document.body,
timeout: globalTimeout,
success: function (response) {
if (response != null ) {
for (var i = 0; i < response.length; i++) {
var appName = response[i].name;
console.log(applicationTabId);
// o/p as {"twitter": "15", "dropbox": "14"}
console.log(appName);
//o/p as twitter
//dropbox
var tabid = applicationTabId.appName;
//var tabid = applicationTabId[appName];
console.log(tabid);
//o/p as undefined
console.log(appName+'---'+tabid);
if (appName in applicationTabId){
}
}
}
},
});
});
}
Apply loop like below:
$.each(applicationTabId, function(key,value){
console.log(key);
console.log(value);
});
Based on code you provided now, change your code like below:
function getapplicationlogouturl(applicationTabId) {
FetchLogoutUrl = {
"applicationName": applicationTabId,
};
$.ajax({
type: "POST",
url: obj.endpoint,
dataType: "json",
data: JSON.stringify(FetchLogoutUrl),
context: document.body,
success: function (response) {
if (response != null ) {
for (var i = 0; i < response.length; i++) {
var appName = response[i].name;
var tabid = applicationTabId[appName];
//print key value data in console to check working fine
console.log(appName+'---'+tabid);
}
}
},
});
}
Note:- var appName and var tabid value will be changed after each iteration happen.
I'm trying to add different set of lat,long in the google visualization table by iterating over the Ajax get response, it looks like only the last value in the response json is added to the row,
Javascript:
$.ajax({
type: 'GET',
url: '/api/v1.0/tasks/'+document.getElementById("autocomplete").value,
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(data){
for(var i=0; i<data.task.length; i++) {
var lat,long,name;
var lat = data.task[i].lat
var longi = data.task[i].longi
var name = data.task[i].markerText
alert(lat,longi,name)
var datag = new google.visualization.DataTable();
datag.addColumn('number', 'lat');
datag.addColumn('number', 'longi');
datag.addColumn('string', 'markerstr');
datag.addRows([[lat,longi,name],]);
}
})
Expected Output:
data = [[37.6153, -122.3900, 'Airport'],
[37.4422, -122.1731, 'Shopping'],]
It looks like you are rebuilding the data structure each time you iterate. It happens that your headers are the same. But in this case the whole data gets re-written on each iteration. Perhaps try something like this.
$.ajax({
type: 'GET',
url: '/api/v1.0/tasks/'+document.getElementById("autocomplete").value,
dataType: 'json',
data: { 'value' : $(this).val() },
success : function(data){
var datag = new google.visualization.DataTable();
datag.addColumn('number', 'lat');
datag.addColumn('number', 'longi');
datag.addColumn('string', 'markerstr');
var rows = []
for(var i=0; i<data.task.length; i++) {
var lat,long,name;
var lat = data.task[i].lat
var longi = data.task[i].longi
var name = data.task[i].markerText
rows.push([lat,longi,name]);
}
datag.addRows(rows);
})
JSON:
[
{
"ID":"25",
"Serial":"1",
"Purchase_id":"8",
"Item":"23",
"Unit":"1",
"HSN":"84212120",
"Quantity":"10",
"Purchase_rate":"100",
"Discount":"10",
"Discount_2":"5",
"Net_rate":"85.5",
"CGST_Percentage":"9",
"SGST_Percentage":"9",
"IGST_Percentage":"0",
"Rate_after_tax":"100.89",
"CGST":"76.95",
"SGST":"76.95",
"IGST":"0",
"Net_amount_without_tax":"855",
"Net_amount":"1008.9"
}
]
jQuery:
$.ajax({
method: "POST",
url: formsubmission,
data: data,
success: function(response) {
var data = JSON.parse(response);
alert(data.ID);
}
})
Anyone can please help me why alert is coming with an undefined message. How can I resolve i8t and How can I alert 25 instead of undefined?
The object is at index 0 of the resulting Array of the parsed response. You can use bracket notation to reference element at index 0 of the JavaScript object
let response =`[{"ID":"25","Serial":"1","Purchase_id":"8","Item":"23","Unit":"1","HSN":"84212120","Quantity":"10","Purchase_rate":"100","Discount":"10","Discount_2":"5","Net_rate":"85.5","CGST_Percentage":"9","SGST_Percentage":"9","IGST_Percentage":"0","Rate_after_tax":"100.89","CGST":"76.95","SGST":"76.95","IGST":"0","Net_amount_without_tax":"855","Net_amount":"1008.9"}]`;
let data = JSON.parse(response);
alert(data[0].ID);
var response =`[{"ID":"25","Serial":"1","Purchase_id":"8","Item":"23","Unit":"1","HSN":"84212120","Quantity":"10","Purchase_rate":"100","Discount":"10","Discount_2":"5","Net_rate":"85.5","CGST_Percentage":"9","SGST_Percentage":"9","IGST_Percentage":"0","Rate_after_tax":"100.89","CGST":"76.95","SGST":"76.95","IGST":"0","Net_amount_without_tax":"855","Net_amount":"1008.9"}]`;
var data = JSON.parse(response);
for (var i = 0; i < data.length; i++) {
alert(data[i].ID);
}
I am fetching data from one list in sharepoint and storing it in json array to pass it onto another function to create a new item in Sharepoint list.The first function is:
$.ajax({
url: someSharepointListUrl,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var array = new Array();
for (var i=0; i< data.d.results.length; i++) {
var it=data.d.results[i];
array.push({
AllLinks: it.AllLinks,
LinkURL: it.LinkURL.Url
});
}
dataCharts=JSON.stringify(array);
alert(dataCharts);
AddDefaultLinks(dataCharts);
},
error: function (data) {
alert(data.responseJSON.error);
}
});
The item is stored in the list as as:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
The second function which fetches data from list after item is created is as follows:
$.ajax({
url: url,
type: "get",
headers: {"Accept": "application/json;odata=verbose"},
success: function (data) {
var c = [];
var stringData = JSON.stringify(data.d.results[0].AllLinks);
//alert(stringData);
c.push(JSON.parse(stringData));
alert(c);
var xonly = c.filter(function (entry){
return entry.AllLinks != x;
});
alert(xonly);
},
error: function() {
alert('fail');
}
});
I need to match if a value exists in this newly created list Item.If yes then delete it eg Lin.
value of c(json array) here is:[{"Name":"Name1","URL":"http://www.name1.com"},{"Name":"Name2","URL":"http://www.name2.com"}]
`
entry.AllLinks doesnt filter data here.AllLinks is undefined in entry.AllLinks.Please help
Use Array.findIndex() to find the desired value inside array, and use Array.splice() method to remove that object.
I would like to two add property Id and ButtonId to the exisiting json result. I have pasted the below js code for reference and I would like to pass the jsonresult to MVC controller. As of now it returns null. please help to proceed. Thanks.
my final result should look like this
json{"Groups":{"Id":"2","ButtonId":"1142","1186","1189"},
{"Id":"3","ButtonId":"1171","1173","1174","1175","1176","1187"},
{"Id":"4","ButtonId":"1177","1178","1179"}} etc..
var btnlist = {Groups: {Id:"", ButtonId: ""}};
$.each($(".buttonData"), function (index, value) {
var values = value.id.split(':');
grpid = values[0].split('-')[1];
btnid = values[1].split('-')[1];
console.log('grpid=' + grpid + ' btnid=' + btnid);
if (typeof (btnlist['Groups'][grpid]) == 'undefined') {
btnlist['Groups'][grpid] = [];
}
btnlist['Groups'][grpid].push(btnid);
});
$.ajax({
type: "POST",
url: "#Url.Action("Home", "Menu")",
dataType: "json",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(btnlist) ,
success: function (result) {
console.log('json' + JSON.stringify(btnlist));
console.debug(result);
},
error: function (request, error) {
console.debug(error);
}
});
This is the json result before pushing into the multidimensional array
The json result, where the properties Id and ButtonId is inserted behind.
null result passed to the controller
With assistance of my colleague, the desired output is as below. This is for other programmers who face similar issue with JSON array. Thanks.
var btnlist = [];
btngrps = $('.btn-sort-container');
$.each(btngrps, function(k, v) {
btnarr = {};
gid = $(this).attr('id');
grpid = gid.split('-')[1];
btnarr.Id = gid.split('-')[1];
btnobjs = $(v).find('.buttonData');
if (btnobjs.length) {
btnarr['btnId'] = [];
$.each(btnobjs, function(bk, bv) {
btnid = $(bv).attr('id').split('-')[2];
btnarr['btnId'].push($(bv).attr('id').split('-')[2]);
});
console.debug(btnarr);
btnlist.push(btnarr);
}
});
console.debug(btnlist);
Output on console
: http://i.stack.imgur.com/oJ3Dy.png