How to load table from $.ajax() request

How to load table from $.ajax() request

rdmrdm Posts: 194Questions: 55Answers: 4

I'm working on a "Hello World" scenario with a simple Web API project.

While I can successfully make an ajax call to my URL and show the results in the console, what I do not yet understand is how to load the $.ajax result into a Data Table.

I have looked at Ajax and it seems the key to loading my table is by use of this function, but I am unclear how to use this function in the case of my specific scenario. The examples I saw looked like they were pulling static files rather than get requests from a URL. (Or maybe I misunderstood what I was looking at.)

     "ajax":function(data, callback, settings) { 
          /*...code... */ 
      }

To provide some more context, here is the full code block: my $,ajax() function that correctly displays the data on the console and the placeholder for the DataTable.

My question is this: how do I make my ajax call within the DataTable() initialization block?

$(() => {   

    // this is the DataTable initializer where I would like to apply the ajax call 
    $(".display").DataTable({
        "ajax":function(data, callback, settings) { 

                // I don't know what to place here

        }
    });

    // this ajax function sends credentials required for authorization
    // and receives the data from the API.

    
    $.ajax({
        url: 'http://testdomain/api/testtables',
        method: "GET",
        xhrFields: {
            withCredentials: true
        },
        success: function (data) {
            // loop data to console to verify it is 
            // arriving to browser 
            
            $.each(data, function(a, b) {
                console.log(b);
            });
        }
    });
    
});

This question has an accepted answers - jump to answer

Answers

  • rdmrdm Posts: 194Questions: 55Answers: 4

    As a disclaimer, I know that I can manually load the table and then initialize the data table, but I was hoping that the separate steps could be avoided by making the ajax call within the Data Tables initialization.

    This, for example creates the desired results, but as I mentioned, takes extra steps. And the Data Table is initialized on the success of the ajax call. It would be nice if I could invert that and inject the ajax call into the Data Table instead.

    $(() => {
        var table = $(".display tbody");
    
        $.ajax({
            url: 'http://testwebsite/api/testtables',
            method: "GET",
            xhrFields: {
                withCredentials: true
            },
            success: function (data) {
                table.empty();
                $.each(data, function (a, b) {
                    table.append("<tr><td>"+b.Campus+"</td>" +
                        "<td>"+b.StudentName+"</td>"+
                        "<td>" + b.StudentId + "</td>" +
                        "<td>" + b.CourseId + "</td>" +
                        "<td>" + b.CourseTitle + "</td>" +
                        "<td>" + b.CreditEarned + "</td>" +
                        "<td>" + b.DateEarned + "</td>" +
                        "<td>" + b.Department + "</td>" +
                        "<td>" + b.ConvertedDepartment + "</td>" +
                        "<td>" + b.School + "</td>" +
                        "<td>" + b.Teacher + "</td></tr>");
                });
    
                $(".display").DataTable();
            }
        });
    });
    
    
  • TooManyTablesTooManyTables Posts: 23Questions: 7Answers: 1
    edited November 2017

    Hey rdm,

    The only difference between pulling from a static file like the one in https://datatables.net/examples/ajax/objects.html and an API point like the one in your OP is that the static file already has the data pre-generated. Assuming you are doing things correctly on the backend, both should deliver data in same format.

    Once your backend script is delivering data in the format DT expects, your front-end will look like this:

    $('.display tbody').DataTable( {
            ajax: {
               url: 'http://testwebsite/api/testtables',
               method: "GET",
               xhrFields: {
                   withCredentials: true
               }
            },
            columns: [
                { data: "b.Campus" },
                { data: "b.StudentName" },
                { data: "b.StudentId" },
                { data: "b.CourseId" },
                { data: "b.CourseTitle" },
                { data: "b.CreditEarned" }
                /*and so on, keep adding data elements here for all your columns.*/
            ]
        } );
    

    What we're doing in the 'columns' section is mapping the returned data to each of the columns in your empty HTML table. If you're returning the data correctly, then that should do the trick.

  • rdmrdm Posts: 194Questions: 55Answers: 4

    I didn't consider using the columns feature. It makes sense. However, the "b." from my example -- shown in yours as well -- refers to the $.each command from my example. In your example, there is no looping function. So I tried this { data: "Campus" } and got an error: DataTables warning: Non-table node initialisation ({tag}).

    Looking at the referring page, I tried this: $(".display").DataTable({... and that error went away. However, the table still ends up blank.

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Could you run your table through the debugger and let me know what the debug trace code is?

    Thanks,
    Allan

  • rdmrdm Posts: 194Questions: 55Answers: 4
    edited November 2017

    @Allan -- I ran the debugger and it brought me here. I see a neat interactive table, but nothing that specifically says "debug data". If the pasted link gives you what you need to know, note that the URL is an intranet site that is closed to everyone outside my domain.

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin

    Thanks.

    That shows me that the initialisation of the DataTable isn't quite right. You've got the Ajax options at the top level, when they should be inside an ajax object. e.g.:

    {
      ajax: {
        "url": "http://london:5001/api/CreditHistories",
        "method": "GET",
        "xhrFields": {
            "withCredentials": true
        }
    }
    

    DataTables isn't seeing your Ajax configuration at all at the moment.

    Allan

  • rdmrdm Posts: 194Questions: 55Answers: 4

    I changed my code as you suggested, but got the same symptom. I ran the debugger again.

    $(() => {
                $(".display").DataTable({
                    ajax: {
                        url: 'http://london:5001/api/CreditHistories',
                        method: "GET",
                        xhrFields: {
                            withCredentials: true
                        }
                    },
                    columns: [
                        { data: "Campus" },
                        { data: "StudentName" },
                        { data: "StudentId" },
                        { data: "CourseId" },
                        { data: "CourseTitle" },
                        { data: "CreditEarned" },
                        { data: "DateEarned" },
                        { data: "Department" },
                        { data: "ConvertedDepartment" },
                        { data: "School" },
                        { data: "Teacher" }
                    ]
                });
            });
    
  • kthorngrenkthorngren Posts: 21,330Questions: 26Answers: 4,951
    edited November 2017 Answer ✓

    Your JSON response isn't in the data object as expected by default:

    [{
        "Id": 1,
        "Campus": "*",
        "StudentName": "*",
        "StudentId": *,
        "CourseId": "*",
        "CourseTitle": "*",
        "CreditEarned": *,
        "DateEarned": "*",
        "Department": "*",
        "ConvertedDepartment": "*",
        "School": "*",
        "Teacher": ""
    }, {
        "Id": 2,
        "Campus"
    ......
    

    You can use the ajax.dataSrc to change the source. In you case your would use "dataSrc": "" like the second example here:
    https://datatables.net/reference/option/ajax.dataSrc#Examples

    Kevin

  • rdmrdm Posts: 194Questions: 55Answers: 4

    Thanks @kthorngren -- That did the trick. Whew!

This discussion has been closed.