WebService and ajax.dataSrc Object Name

WebService and ajax.dataSrc Object Name

TinoTranTinoTran Posts: 3Questions: 1Answers: 0

Hello,

I'm having some slight trouble with the ajax.dataSrc function. It appears that it will only accept "data" and "aaData" for the array/object name. Is there a way to override this?

I'm currently utilizing a web service to return the desired JSON results back for the table. However, the issue I am running into is that the JSON returned uses the a different name. Is it possible to override the "data" and/or "aaData"?

Below is an example of what our JSON returned result.

{
"employees": [
{
"FirstName": "Tiger",
"LastName": "Nixon",
"Position": "System Architect",
"Office": "Edinburgh",
"Salary": "$320,800"
},
{
"FirstName": "Garrett",
"LastName": "Winters",
"Position": "Accountant",
"Office": "Tokyo",
"Salary": "$170,750"
},
{
"FirstName": "Donna",
"LastName": "Snider",
"Position": "Customer Support",
"Office": "New York",
"Salary": "$112,000"
}
]
}

The code I'm using to trigger this is inside a jQuery button click function.

$("#btnCplSearch").click(function () {
var method = "GetDocuments";
var keyword = $("#txtSearchTerm").val();

    if (keyword == "")
        {
            ErrorMsg("No Keyword found.")
            //GetData("GetDocuments", "keyWords=test", true, true)
        }
        else {

            var wsUrl = "http://localhost/ClinicalDocsSearch/DocumentSearch.svc/" + method + "?" + "keyWords=" + keyword;

        dt.clear();

            dt.ajax.url(wsUrl);

        dt.draw();

        dt.ajax.reload();

    }

});

Thanks in advance!

This question has an accepted answers - jump to answer

Answers

  • tangerinetangerine Posts: 3,352Questions: 37Answers: 394

    I'm having some slight trouble with the ajax.dataSrc function. It appears that it will only accept "data" and "aaData" for the array/object name. Is there a way to override this?

    ajax.dataSrc provides the option to define your own string.
    https://datatables.net/reference/option/ajax.dataSrc

  • TinoTranTinoTran Posts: 3Questions: 1Answers: 0

    Hello!

    I've been looking at that page and can't seem to wrap my head around it. If I utilize it exactly as it is on the page on initialization, it works. I can define it. However, I'm trying to define it on the fly after the dataTable has been initialized. using

    $('#cplSearchResult').DataTable.ajax.dataSrc("GetDocumentsResult");

    doesn't give me any errors, but any javascript I put after this line does not fire. And Thanks for the quick reply!!!

  • bindridbindrid Posts: 730Questions: 0Answers: 119

    is GetDocumentsResult a function? then try

    $('#cplSearchResult').DataTable.ajax.dataSrc(function(result) {GetDocumentsResult (result);})

    GetDocumentsResult(result){
    return result.employees;
    }

  • allanallan Posts: 62,044Questions: 1Answers: 10,171 Site admin

    Are you using the ajax option to configure the DataTable with the Ajax URL?

    If so, use:

    ajax: {
      url: ...,
      dataSrc: 'employees'
    }
    

    That just tells DataTables the data array is in the employees parameter.

    Allan

  • TinoTranTinoTran Posts: 3Questions: 1Answers: 0

    @Bindrid - Thanks! I'll modify the above and give it a try. The first attempt didn't work but maybe I missed something on my end.

    @allan - I'm trying to use the ajax option but the table needs to be empty when the page initially loads. The table only loads when someone does a search. When I leave the url blank on the load provides an error. I'm dynamically trying to load the URL that connects to a web service to pull the results.

    If I'm not mistaken, the code piece in your comment only works on the initialization of the datatable.

  • bindridbindrid Posts: 730Questions: 0Answers: 119
    Answer ✓

    Here is something I did to keep things simple.
    I tend to put my table declarations in a function to make it easier to reuse.
    In this case in particular I have to be able to switch between single and multi selects.
    This is a search page to find system users (the search text is applied against there user name, email, formal name, etc).

    My Web Method:

            [WebMethod(EnableSession=true)]
            public string FindUser(string Search, Boolean IncludeInactive)
            {
                try
                {
                    uwLog4.Debug(this);
                    // System.Threading.Thread.Sleep(5000);
                    List<doUserInfo> users = bllUserInfo.FindUsers(Search, IncludeInactive);
                    string list = JsonConvert.SerializeObject(users);
                    return list;
                }
                catch (Exception ex)
                {
                    uwLog4.Error(ex);
                    throw ex;
                }
            }
    

    Note: I pulled off the keydown/keypress put on by Datatable and replaced it with my own. User has to click a button or hit the button to fire off the ajax reload. So for my button click event handler I have:


    btn.on("click", function () { $("#tblFindUser").DataTable().ajax.reload(); });

    And my table declaration. In particular note how I did the ajax section.

    /**
     * Get table definition for the base FindUser table
     */
    UWFindUsers.getTableDefinition = function (me) {
        // this function just builds the url needed based on paramters.
        var url = getBasePath("ws", "wsUWUser", "FindUser");
        var columns = [
            { data: "DisplayText", title: "Name", width: "300px" },
            { data: "OrgCode", title: "Org Code", width: "150px" },
            {
                data: "isActive", title: "Active", width: "150px",
                // Show a checkmark on active users
                 render: function (data) { return data == true ? '<i class="fa fa-check fa-2"></i>' : ''; }
            }
        ];
    
        var dataTableDeclaration = {
            dom: "<'uwfuTop-dt'f><'dataTables_processing'>tB",
            columns: columns,
            ajax: function (data, callback, settings) {
                var sertext = $(".uwfuTop-dt input[type=search]").val();
                // I require at least 3 characters or to many rows will be returned.
                if (sertext.length  < 4 ) {
                    // prevent an empty search from being generated because 
                    // the ajax will fail because to much data.
                    callback({ data: [] });
                }
                else {
                    // clear table prior to search, then tell user processing....
                    // (we have a slow network)
                    me.dataTable.clear().draw();
                    $('.dataTables_processing', $('#tblFindUser').closest('.dataTables_wrapper')).show();
                    $("#tblFindUser").find(".dataTables_empty").hide();
    
                    // Ajax returns a promise, or you can use your own as I do 
                    // but this is just an ajax call so i did not include it
                    me.getUwUsersList(sertext).done(function (resp) {
                        // warning messages on result set, etc
                        if (resp.length > 1000) {
                            $("#divUwFuSearchMessage").html("<span style='color:red'>Max user count exceeded, please refine your search</span>");
                        }
                        else {
                            $("#divUwFuSearchMessage").html(resp.length + " Users Found");
                        }
                        $('.dataTables_processing', $('#tblFindUser').closest('.dataTables_wrapper')).hide();
                        callback({ data: resp });
                    })
                }
            },
            pageLength:1002, // Stored proceedure max is 1001
            serverSide: false,
            deferLoading:0,
            scrollCollapse:false,
            scrollY: 400,
            deferRender: false,
            select: { style: (me.multiSelect ===true?"multi":"single") },
            buttons: [{
                // display the details of a selected user 
                text: "Details", extend: "selectedSingle", action: function (e, dt, button, config) {
                    var rowData = dt.row({ selected: true }).data();
                    me.showFinderDetailDialog(null, rowData.uiid);
                    }
                },
                // button to return the selected user to the parent form
                {
                    text: "Select", extend: "selectedSingle", action: function (e, dt, button, config) {
                        var rowData = dt.row({ selected: true }).data();
                        me.getUserInfoDetails(rowData.uiid).done(function (user) { me.resolveAndCloseSearch(user) });
                    }
                }
            ]
        };
        // Add multi select button in multi select mode
        if (me.multiSelect === true) {
            dataTableDeclaration.buttons[parms.buttons.length] = {
                text: "Multi-Select", extend: "selected", action: function (e, dt, button, config) {
                    var rowData = dt.rows({ selected: true }).data();
                    me.getMultiUserInfoDetails(rowData).done(function (user) { me.resolveAndCloseSearch(user) });
                }
            }
        }
        // add this button when multi select is turned on
        dataTableDeclaration.buttons[dataTableDeclaration.buttons.length] = { text: "Cancel", action: function () { me.resolveAndCloseSearch(null); } };
        return dataTableDeclaration;
    
    }
    
This discussion has been closed.