0

I'm trying to populate a table when a user clicks another table's row. I have an onClick event in the <tr> tag of the first table which fires a function to send three properties to my webapi. I have a named handler which takes the three properties and uses them as input values to another method to retrieve data from Azure Tables. The response is pre-formatted JSON data which I feed to the JavaScript code.

What I'm seeing in my rendered view is a long string of JSON text; no columns or rows at all. According to the documentation I should be able to bind the dataSet to the data value of the DataTable and build the table dynamically.

JavaScript:

function GetActivityLog(pk, rk, cn) {
    var dataSet = $('#tblActivityLogs').load('/Nodes?handler=ActivityLog' + '&PartitionKey=' + pk + '&RowKey=' + rk + '&ComputerName=' + cn);
    $('#tblActivityLogs').DataTable({
        "ajax": {
        url: '/Nodes?handler=ActivityLog' + '&PartitionKey=' + pk + '&RowKey=' + rk + '&ComputerName=' + cn,
        data: dataSet
        }
    });
    console.dir(dataSet);
}

$(document).ready(function () {
$('#tblActivityLogs').DataTable({
    "order": [[0, "desc"]],
    columnDefs: [
            {
                targets: 0,
                className: 'dt-body-nowrap'
            }
        ]
    });
})

Razor/HTML:

<tr onmouseover="" style="cursor: pointer;" role="button" id="getActivtiy" onclick="GetActivityLog('@item.PartitionKey','@item.RowKey','@item.ComputerName');">

HTML Table:

<div class="row">
    <div class="col-lg-12">
        <table id="tblActivityLogs" class="display"></table>
    </div>
</div>

C# code:

public async Task<ContentResult> OnGetActivityLog([FromQuery] string PartitionKey, string RowKey, string ComputerName)
{
    Activities = await _azureTableConnection.GetActivitiesAsync(PartitionKey, RowKey, ComputerName);
    return Content(JsonConvert.SerializeObject(new { Activities }));
}

console.dir(dataSet) output:

output

UPDATE:

Set a breakpoint before the ajax call to test the function and input values but still get an (undefined) error.

4
  • 1
    Hi @Jason, can you add a console.dir(dataSet) in your GetActivityLog function and add the output to your question? Commented Oct 10, 2018 at 20:25
  • You bet. Done and done. What's interesting is that the dataSet appears to be a table object itself and not the raw JSON I would have thought. Maybe I shouldn't be doing a $('#tblActivityLogs').load? Commented Oct 10, 2018 at 20:30
  • Let me answer your question. Commented Oct 10, 2018 at 20:35
  • I edited your question in order to not expose the secret information. Commented Oct 10, 2018 at 21:39

2 Answers 2

1

You just need some minor changes on your code:

function GetActivityLog(pk, rk, cn) {
 $.ajax({
  url:'/Nodes?handler=ActivityLog' + '&PartitionKey=' + pk + '&RowKey=' + rk + '&ComputerName=' + cn
 }).done(function(response){
   $('#tblActivityLogs').DataTable( {
     data: response
   });
 });
}
Sign up to request clarification or add additional context in comments.

5 Comments

This looks better but my table is blank now. Looking in Chrome's Preview pane I can see three entities and they all look to be formatted correctly. I ran into this same issue with another variation of my code when I was trying the same thing with partial views in Razor pages. Any ideas?
Can you call the function from the console tab with working parameters in order to check if it works...just for testing purposes
good suggestion. If I set a breakpoint at $.ajax I can see my three input properties being passed. At that point I copy/paste in the entire function (above) and I get "undefined".
On the console tab try calling the function with just GetActivityLog(pk, rk, cn) replacing pk, rk and cn with the right parameters. Just to see if the function gets called and the datatable gets populated.
Updated original post with image (same undefined result).
0

As per 'Kevin's' post (https://datatables.net/forums/discussion/comment/136685/#Comment_136685), along with @Hackerman's suggestions, I finally have a working solution.

  1. In order to build a table dynamically in the way I was trying, you MUST define column values when building the DataTable object.
  2. You can't use ajax.reload() or DataTables().destroy() or any other method if you're not using the ajax: keyword (see Kevin's post). If you try to use the ajax.reload() method after populating the table with data you'll get an invalid JSON error.
  3. You need to clear the table, then add the rows of json content, then draw it again for each click event.
  4. Instead of waiting for the .done to fire an anonymous function, I used the success tag to kick it off.

Here is the final solution:

    function GetActivityLog(pk, rk, cn) {
        $.ajax({
            url: '/Nodes?handler=ActivityLog' + '&PartitionKey=' + pk + '&RowKey=' + rk + '&ComputerName=' + cn,
            success: function (json) {
                table = $('#tblActivityLogs').DataTable({
                    "order": [[0, "desc"]],
                });
                table.clear();
                table.rows.add(json).draw();
            }
        })
    }

    $(document).ready(function () {
        $('#tblActivityLogs').DataTable({
            "order": [[0, "desc"]],
            columnDefs: [
                { targets: 0, className: 'dt-body-nowrap', title: 'Date/Time', data: 'timestamp' },
                { targets: 1, title: 'Computer', data: 'computerName' },
                { targets: 2, title: 'Type', data: 'entryType' },
                { targets: 3, title: 'Event ID', data: 'eventid' },
                { targets: 4, title: 'Message', data: 'message' }
            ]
        });
    })

BONUS:

You CAN actually load the table in advance of populating data, and you don't need the <thead> or <tr/td> tags either; just an open/close <table> tag with the correct ID matching the onClick event. I was able to correctly format the table with the right title and data bindings.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.