What is the syntax to use Child rows with AJAX?

What is the syntax to use Child rows with AJAX?

dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

Hello everyone,

So I'm trying to add to my table the child rows like in this example: https://datatables.net/examples/api/row_details.html but I want to use AJAX to retrieve the data. I know there is an AJAX example but imo it doesn't explain well the syntax: https://www.datatables.net/blog/2017-03-31.

The end result is that I want the child row to look exactly as the first link (i.e. 'Full name: Insert Name Here') but getting the data from AJAX so 'Full name' is a column in a database and 'Insert Name Here' is the row. Unfortunately the second link, which is an example using AJAX, provides a complete different example and I can't seem to understand the syntax in there so I'm unable to retrieve the data.

Here is what I have so far:

    <script>
        $(document).ready(function () {
            var table = $('#dtBasicExample').DataTable({
                ajax: {
                    method: 'GET',
                    url: 'https://insertaddresshere.amazonaws.com/prod',
                    dataSrc: ''
                },
                columns: [
                    {
                        "className": 'details-control',
                        "orderable": false,
                        "data": null,
                        "defaultContent": ''
                    },
                    { "data": "ID" },
                    { "data": "Title" },
                    { "data": "Date" }
                ]
            });
            $('.dataTables_length').addClass('bs-select');
            $('#dtBasicExample tbody').on('click', 'td.details-control', function () {
                var tr = $(this).closest('tr');
                var row = table.row(tr);

                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    row.child(format(row.data())).show();
                    tr.addClass('shown');
                }
            });
        });
    </script>

And then the function format which is where the issue is and I'm not sure about the syntax (I do put the function before the one on top) I ask questions in comments (//) inside the code specifying my confusion:

    <script>
        function format(rowData) {
            var div = $('<div/>')
                .addClass('loading')
                .text('Loading...');

            $.ajax({
                method: 'GET',
                url: ' https://insertaddresshere.amazonaws.com/prod',
                // Here is my first confusion. What does the following 'data' mean? It is not the {"data: "ID"} from the first ajax call 
                // that is setting up the columns, right?
                data: {
                    Title: rowData.Title
                },
                 // Is the dataType even necessary? I don't use it originally and I'm always able to retrieve the ajax data when not 
                 // doing the child rows.
                dataType: 'json',
                // Where does the json from inside the function comes from? where does the json.html file comes from as well? 
                // What's in that file? And most importantly, where do I write the <table> like in the first non-ajax example, I'm 
                // assuming is inside the success: function, right?
                success: function (json) {
                    div
                        .html(json.html)
                        .removeClass('loading');
                }
            });

            return div;
        }
    </script>

As you may have notice with the questions inside the code, is mostly a non-understanding of the syntax of datatables child rows with ajax. Can anyone help me with achieving the same results as https://datatables.net/examples/api/row_details.html but using ajax instead?

Thanks in advance.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736
    edited August 2019

    The ajax method used is the standard [jQuery ajax()](https://api.jquery.com/jquery.ajax/] method. If you have questions about the general usage of ajax please refer to the doc.

    What does the following 'data' mean?

    This is the unique data from each row that you can send to the server. It is expected the server script, at the URL specified, can query the source data using the unique ID. Is ID or Title unique? Which ever is unique is the one to use.

    Is the dataType even necessary?

    Maybe not but it really depends on your environment. please refer to the above ajax docs.

    where does the json.html file comes from

    The example, from the blog link you posted, is using div.html( json.html ) as a simple way to show that your server script can return HTML formatted data and it can simply be placed in a div or whatever using jQuery. your server script can return something other than HTML data it can be a data structure that is the same as your original ajax request. You would then parse it like the format function in the first example.

    To make this work you need to first determine what unique data point, from each row, to send to the server. This is the data parameter. Then you need to decide what format you want to return the JSON data and in the ajax success function parse appropriately to display in the chid row.

    HTH, please post any questions.

    Kevin

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

    Thanks for your reply!

    What does the following 'data' mean?

    This is the unique data from each row that you can send to the server. It is expected the server script, at the URL specified, can query the source data using the unique ID. Is ID or Title unique? Which ever is unique is the one to use.

    But would this always be necessary? Is it needed for the child-row? Here is the thing, I plan on using the second AJAX call the same way I used the first one. So for example, without the child rows, this is how I do the ajax call:

        <script>
            $(document).ready(function () {
                $('#dtBasicExample').DataTable({
                    ajax: {
                        method: 'GET',
                        url: 'https://insertaddresshere.amazonaws.com/prod',
                        dataSrc: ''
                    },
                    columns: [
                        { "data": "ID" },
                        { "data": "Title" },
                        { "data": "Date" }
                    ]
                });
                $('.dataTables_length').addClass('bs-select');
            });
        </script>
    

    And it works perfectly. I didn't use the 'data' there. If I plan to use the "same" call with the "same" structure, would the 'data' code be needed? If so then the ID would be the unique data for each row. I'm just a little confuse since I intend to call the ajax the same way as I do without using the child row and in that case I never use the 'data' code (except the one inside the column). So is the 'data' a child-row requirement?

    BTW, just to give an example, I plan on calling columns 'ID', 'Title', and 'Date' in the original row, and then the child-row should call for different columns as data for example 'Name', 'Department', 'Org'. So the father-child would have different data but the call should be done the same.

    Thanks in advance.

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    I intend to call the ajax the same way as I do without using the child row and in that case I never use the 'data' code (except the one inside the column). So is the 'data' a child-row requirement?

    The purpose of using the data parameter with a unique ID is so that each child ajax request doesn't return all the data in the table. The ajax response will have only the data for that row. Otherwise all of the table data will be returned each time you open a child row. Probably not what you want.

    If I plan to use the "same" call with the "same" structure, would the 'data' code be needed?

    If you use the same call then how would the server know whether to return 'ID', 'Title', 'Date' or 'Name', 'Department', 'Org'? A different URL/call is probably needed so you know what data to return.

    A simpler approach would be to return all the data in the original ajax option request. So the response would have 'ID', 'Title', 'Date', 'Name', 'Department', 'Org'. This is like the first example you posted. Is there a reason you don't want to do this and prefer the ajax option?

    Kevin

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

    A simpler approach would be to return all the data in the original ajax option request. So the response would have 'ID', 'Title', 'Date', 'Name', 'Department', 'Org'. This is like the first example you posted. Is there a reason you don't want to do this and prefer the ajax option?

    Well that example uses ajax for the original row, and then static html for the child row. I can't use that since the original row should not have all the information. Instead, some information should be in the original row (i.e. ID, Title, Date) as ajax call and other data should be in the child-row as ajax call (i.e. Name, Department, Org).

    The purpose of using the data parameter with a unique ID is so that each child ajax request doesn't return all the data in the table. The ajax response will have only the data for that row. Otherwise all of the table data will be returned each time you open a child row. Probably not what you want.

    Ok, yeah that make sense. So do you know the syntax of data? Example:

                data: {
                    Title: rowData.Title
                },
    

    I'm just a little confused about the syntax. What represents the left side i.e. Title? is it the unique primary key? and the right side I supposed is that specific column you want to show? So for example, would it be something like this in my case?:

                    data: {
                        ID: rowData.Name
                        // ID is the unique primary key, and Name is the column I want to show
                    },
    

    Thanks in advance.

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736
    edited August 2019
    data: {
        Title: rowData.Title
    },
    

    This would pass a parameter Title to your server with the value contained in rowData.Title which would be the unique value. The server script would then extract the parameter and use the value to request the Name, etc corresponding to the rowData.Title value.

    data: {
        ID: rowData.Name
        // ID is the unique primary key, and Name is the column I want to show
    },
    

    This would not work because you don't have the Name field as part of your row data.

    Kevin

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0
    edited August 2019

    Thanks, I think I now understand the 'data' code and what you meant. So in that case I don't think I need to use it and now I understand why not using it (when doing the normal ajax call without the child-row) hasn't affected anything. I guess I forgot to mention that I'm using API Gateway and Lambda. So basically, I'm not sending anything to the server. I'm using the URL from API Gateway in which it activates a GET call and in which I don't send any data and then it activates the Lambda function in which it runs a query retrieving the specific data I need from the database and then sending it back to the user. That whole process has a URL in which I put in the URL code and in turn I receive the specific data I need thanks to Lambda in JSON format (i.e. the JSON data of Name, Department, and Org).

    So I think I can eliminate data and dataType from the code. It now looks like this:

        <script>
            function format(rowData) {
                var div = $('<div/>')
                    .addClass('loading')
                    .text('Loading...');
    
                $.ajax({
                    method: 'GET',
                    url: ' https://insertaddresshere.amazonaws.com/prod',
                     // So here inside the success: function is where I assume the last piece is 
                     // needed.
                    success: function (json) {
                        div
                            .html(json.html)
                            .removeClass('loading');
                    }
                });
    
                return div;
            }
        </script>
    

    Any idea how to implement the child-row like it appears in here https://datatables.net/examples/api/row_details.html but with ajax call in the child-row? I'm thinking the table goes inside the format (not sure if inside the success:function though?) like in the example but I'm not sure how to include the data I'm receiving from the ajax URL into the table inside the format function. I already should be receiving the data I need thanks to the URL (i.e. Name, department, Org) so what I need to figure out is what is the syntax to say "Add these data that I'm receiving from the URL into that table inside the format function". I think is probably very similar than the non-child version ajax, I just can't seem to figure out how. Do you have some ideas how I can make this happen?

    Thanks.

  • colincolin Posts: 15,112Questions: 1Answers: 2,583

    This thread has a child row being display with data from a separate ajax call, so hopefully should help.

    Cheers,

    Colin

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736

    It looks like you are using the same URL to get the original table data and to get the child row data: https://insertaddresshere.amazonaws.com/prod

    Since you aren't sending any parameters it would seem to me that the original data will also contain Name, department, Org. Is this true?

    I think is probably very similar than the non-child version ajax, I just can't seem to figure out how. Do you have some ideas how I can make this happen?

    I suspect its exactly the same with the same data including both (ID, Title, Date) and (Name, department, Org). You can verify what is returned by using the browser's developer tools. This tech note explains how. I would look at both the request from the original data and the child rows. What do you see in both cases?

    Kevin

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

    It looks like you are using the same URL to get the original table data and to get the child row data: https://insertaddresshere.amazonaws.com/prod

    Since you aren't sending any parameters it would seem to me that the original data will also contain Name, department, Org. Is this true?

    So after several testing I found out that there's two ways of doing it. I can either call all the columns (i.e. ID, Title, Date, Name, department, Org) on the first ajax call for the parent row and then use that data for the child row without making a second ajax call on that child row, so basically like this example: https://datatables.net/examples/api/row_details.html. In that case, I was able to do it. Here's the code:

        <script>
            function format(d) {
                // `d` is the original data object for the row
                return '<table cellpadding="5" cellspacing="0" border="0" width="100%" style="padding-left:50px;" class="text-left">' +
                    '<tr>' +
                        '<td>Name:</td>' +
                        '<td>' + d.Name + '</td>' +
                    '</tr>' +
                    '<tr>' +
                        '<td>Department:</td>' +
                        '<td>' + d.department + '</td>' +
                    '</tr>' +
                    '<tr>' +
                        '<td>Org:</td>' +
                        '<td>' + d.Org + '</td>' +
                    '</tr>' +
                '</table>';
            }
        </script>
    
    <script>
        $(document).ready(function () {
            var table = $('#dtBasicExample').DataTable({
                ajax: {
                    method: 'GET',
                     // In this URL I'm getting all the data from all the columns
                    url: 'https://insertaddresshere.amazonaws.com/prod', 
                    dataSrc: ''
                },
                columns: [
                    {
                        "className": 'details-control',
                        "orderable": false,
                        "data": null,
                        "defaultContent": ''
                    },
                    { "data": "ID" },
                    { "data": "Title" },
                    { "data": "Date" }
                ]
            });
            $('.dataTables_length').addClass('bs-select');
            $('#dtBasicExample tbody').on('click', 'td.details-control', function () {
                var tr = $(this).closest('tr');
                var row = table.row(tr);
    
                if (row.child.isShown()) {
                    row.child.hide();
                    tr.removeClass('shown');
                }
                else {
                    row.child(format(row.data())).show();
                    tr.addClass('shown');
                }
            });
        });
    </script>
    

    However, there's also a second way of doing it that I'm more interested in. And that way is having the first ajax call of the parent row to call only the columns to be display on that row (i.e. ID, Title, Date), that ajax will have a URL in which the Lambda function will only return those three data. And then also having a second ajax call for the child-row that will have a different URL in which the Lambda function will return the three columns of that row (i.e. Name, department, Org).

    Here is what I have so far, I feel I'm close and just need to fix the syntax. Here's the code:

        <script>
            // the rowData won't be used since I won't use the data on the parent row table
            // but I have it there just because
            function format(rowData) {
                var div = $('<div/>')
                    .addClass('loading')
                    .text('Loading...');
    
                $.ajax({
                    method: 'GET',
                    url: 'https://thisIsASecondURL.amazonaws.com/prod',
                     // I'm now putting the JSON data inside the function in Success
                    success: function (data) {
                         // Assign the data parsed as a JavaScript object into xdataInfo. Maybe
                         // here is a syntax error?
                        var xdatainfo = JSON.parse(data);
                         // I'm now following the syntax of the example but this very well could
                         // be written incorrectly with syntax error. For now I just want to see if
                         // the data can show on the child-row, I will then display it accordingly
                         // in a table
                        div
                        + '<p>' + xdatainfo.Name + '</p>'
                            .removeClass('loading');
    
                    }
                });
    
                return div;
            }
        </script>
    

    Any hints on any error of this code and how can I fix it? (I Left comments inside the cod explaining/asking things). The output format would be different, since I want it in a table but for now I just want to see the child row display is data.

    Thanks.

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0
    This thread has a child row being display with data from a separate ajax call, so hopefully should help.
    
    Cheers,
    
    Colin
    

    Thanks. So for now, I'm trying to display the data for the child row. Here is what I have so far:

    <script>
        // the rowData won't be used since I won't use the data on the parent row table
        // but I have it there just because
        function format(rowData) {
            var div = $('<div/>')
                .addClass('loading')
                .text('Loading...');
    
            $.ajax({
                method: 'GET',
                url: 'https://thisIsASecondURL.amazonaws.com/prod',
                 // I'm now putting the JSON data inside the function in Success
                success: function (data) {
                     // Assign the data parsed as a JavaScript object into xdataInfo. Maybe
                     // here is a syntax error?
                    var xdatainfo = JSON.parse(data);
                     // I'm now following the syntax of the example but this very well could
                     // be written incorrectly with syntax error. For now I just want to see if
                     // the data can show on the child-row, I will then display it accordingly
                     // in a table
                    div
                    + '<p>' + xdatainfo.Name + '</p>'
                        .removeClass('loading');
    
                }
            });
    
            return div;
        }
    </script>
    

    Any hints on any error of this code and how can I fix it? (I left comments inside the code explaining/asking things). The output format would be different, since I want it in a table but for now I just want to see the child row display is data.

    Thanks.

  • kthorngrenkthorngren Posts: 20,144Questions: 26Answers: 4,736
    Answer ✓
                    div
                    + '<p>' + xdatainfo.Name + '</p>'
    

    div is a jQuery object representing a div. Your syntax is incorrect. This is what the ajax example has:

                    div
                        .html(json.html)
    

    What you want is something like this:

                    div
                        .html( '<p>' + xdatainfo.Name + '</p>' )
    

    Kevin

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

    What you want is something like this:

    div
        .html( '<p>' + xdatainfo.Name + '</p>' )
    

    Kevin

    Thanks a lot! I had to fix some other code as well like for example I had to remove JSON.parse since the data was already a JS Object. I thought it was JSON but apparently JS object can have double quotations on both the keys and the values and datatables seem to take them fine. Anyhow here is the functional code:

        <script>
            function format(rowData) {
                var div = $('<div/>')
                    .addClass('loading')
                    .text('Loading...');
    
                $.ajax({
                    method: 'GET',
                    url: ' https://secondURLgoeshere.amazonaws.com/prod',
                    dataSrc: '',
                    success: function (data) {
                        var xdatainfo = data;
                        div
                            .html('<p>' + xdatainfo.Name + '</p>')
                            .removeClass('loading');
    
                    }
                });
    
                return div;
            }
        </script>
    

    I will now work on making the child rows look like this example which I believe uses a table inside: https://datatables.net/examples/api/row_details.html. But now that I have the AJAX child row syntax, it should hopefully be easy.

    Thanks again!

This discussion has been closed.