Mohemmad K
Mohemmad K

Reputation: 839

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?

Upvotes: 0

Views: 962

Answers (1)

Rudie Visser
Rudie Visser

Reputation: 580

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.

Upvotes: 1

Related Questions