Mohemmad K Mohemmad K - 1 year ago 142
Javascript Question

How to build JSON string for JQuery DataTable?

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.

enter image description here

What am I missing?

Answer Source

I assume 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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download