How to activate ajax by clicking a button?

How to activate ajax by clicking a button?

dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

Hello,

So what I'm trying to do is for the table to be in display when I enter the page (meaning the show entries, search bar, thead, tfooter, next pages, etc - all be visible) but no data showing meaning that the ajax call can only be activated when the user clicks a button, instead of the default document.ready. Any idea how to do this? Most responses I found online is done either by a previous version or doesn't work. Thanks in advance.

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769
    edited September 2019 Answer ✓

    Here is a simplified example based on the config in your other post:
    http://live.datatables.net/huyexejo/121/edit

    Note it starts with temp data just to show the table is cleared and reloaded with the newly fetched data.

    Kevin

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

    Thanks for the response.

    I entered the code, erased the JSON.parse cause I'm already receiving an object, but I'm getting this error:

    datatables.min.js:2 Uncaught TypeError: Cannot read property 'length' of undefined
        at l.<anonymous> (datatables.min.js:2)
        at l.iterator (datatables.min.js:2)
        at l.<anonymous> (datatables.min.js:2)
        at Function.add (datatables.min.js:2)
        at Object.<anonymous> (it points to this:  table.rows.add(result.data).draw();)
        at Object.fireWith [as resolveWith] (jquery-3.4.1.min.js:2)
        at l (jquery-3.4.1.min.js:2)
        at XMLHttpRequest.<anonymous> (jquery-3.4.1.min.js:2)
    

    Here is my code:

    <script>
            function format(d) {
                return '<table cellpadding="5" cellspacing="0" border="0" style="padding-left:50px;">' +
                    '<tr>' +
                    '<td>Description:</td>' +
                    '<td>' + d.Comments + '</td>' +
                    '</tr>' +
                    '</table>';
            }
        </script>
    
        <script>
            var table;
    
            function getDT() {
                var searchData = {
                    "testID": $('input[name=testID]').val()
                };
                $.ajax({
                    Type: 'GET',
                    url: 'https://enteraddresshere.amazonaws.com/prod',
                    data: searchData,
                    dataSrc: ''
                }).done(function (result) {
                    console.log(typeof result);
                    //result = JSON.parse(result);
                    table.clear();
                    table.rows.add(result.data).draw();
                });
            }
    
            $(document).ready(function () {
                table = $('#dtBasicExample').DataTable({
                    columns: [
                        {
                            "className": 'details-control',
                            "orderable": false,
                            "data": null,
                            "defaultContent": ''
                        },
                        {
                            "data": function (row, type, set) {
                                return row.example + " - " + row.example2
                            }
                        },
                        { "data": "example3" },
                        { "data": "example4" },
                        { "data": "example5"},
                        { "data": "example6" },
                        { "data": "example7" },
                        { "data": "example8" },
                        {"data": "example9"},
                        {"data": "example10"},
                        { "data": "exqmple11" }
                    ]
                });
    
                $('#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');
                    }
                });
    
                $('#btnSearch').on('click', function () {
                    getDT();
                });
            })
        </script>
    

    Looks like there's an issue with table.rows.add(result.data).draw(); any idea how to fix it? Thanks.

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

    Ok so is working now (had to erase the .data of result.data) but the same issue is happening than the one on my previous post: https://datatables.net/forums/discussion/58085/how-to-stop-page-from-refreshing-when-submitting-ajax-through-btn-click.

    So it looks like your code, as well as the code in that post does work BUT it has that refresh effect which is not good. The common denominator seem to be the done() and draw(). Is there another way of doing it rather than using done() and draw()?

    I'm gonna try to explain the issue in detail. When I enter the data on the input field (testID), for example, '2', and click the search button, the page doesn't refresh per se but it goes all the way on top, the URL changes from .html to .html?etcetc but there's no data and nothing on developer tools. I then enter 2 again on the testID input field and click search button and everything works good and table data loads. If I then change the data and instead enter 3 and then press enter, again the page goes to the top, URL changes, no data, and nothing on developer tool. I enter again the 3 and everything works fine. This is so strange. How exactly does done() and draw() work? I'm 90% sure that's where the issue is. Is there another way of doing it?

    PS: I really wish this functionality of pressing a button to load ajax data had a clear explanation on the docs. Most people click a button to search the database and display results in datatables, as opposed to all data being available on document.ready.

    Anyhow I appreciate your help! and if you know a solution feel free to let me know. I'll keep trying in the meantime.

  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769

    table.rows.add(result.data).draw();

    The data you add is specific to what you receive. My example is using the Datatables environment which returns the data in the data object. Take a look at the browser's developer tools > Network > Preview to see the response in my test case and compare to the response in your system. You likely will just want what you had before which is table.rows.add(result).draw();.

    Kevin

  • dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

    Ok so is working now (had to erase the .data of result.data) but the same issue is happening than the one on my previous post: https://datatables.net/forums/discussion/58085/how-to-stop-page-from-refreshing-when-submitting-ajax-through-btn-click.

    So it looks like your code, as well as the code in that post does work BUT it has that refresh effect which is not good. The common denominator seem to be the done() and draw(). Is there another way of doing it rather than using done() and draw()?

    I'm gonna try to explain the issue in detail. When I enter the data on the input field (testID), for example, '2', and click the search button, the page doesn't refresh per se but it goes all the way on top, the URL changes from .html to .html?etcetc which means that a call happened and I did see for less than one second on the developer tools the call but it then disappears resulting in no data and nothing on developer tools. I then enter 2 again on the testID input field and click search button and everything works good and table data loads. If I then change the data and instead enter 3 and then press enter, again the page goes to the top, URL changes, dev tools shows call for less than a second and then disappears, no data, and nothing on dev tools. I enter again the 3 and everything works fine. This is so strange. How exactly does done() and draw() work? I'm 90% sure that's where the issue is. Is there another way of doing it?

    PS: I really wish this functionality of pressing a button to load ajax data had a clear explanation on the docs. Most people click a button to search the database and display results in datatables, as opposed to all data being available on document.ready.

    Anyhow I appreciate your help! and if you know a solution feel free to let me know. I'll keep trying in the meantime.

    UPDATE: Developer Tools does show the call being received for less than 1 second but it then disappears, resulting in no data and nothing on dev tools.

  • kthorngrenkthorngren Posts: 20,302Questions: 26Answers: 4,769

    When I enter the data on the input field (testID), for example, '2', and click the search button, the page doesn't refresh per se but it goes all the way on top, the URL changes from .html to .html?etcetc which means that a call happened

    What do you mean by "but it goes all the way on top"?

    the URL changes from .html to .html?etcetc which means that a call happened

    If you are executing an ajax call the URL isn't going to change. Something else must be happening on your page that isn't reflected in the code you posted. You have the console.log(typeof result); statement in your done function. Do you see output from it when you click the button? I recommend you add more console.log statements at various places, like in your click event and getDT function to see how the code flows when you click the button.

    If you aren't able to post a link to your page then my suggestion would be to build up the test case I provided with your code to demonstrate the problem. At this point without being able to see the problem it will be difficult to suggest solutions.

    I really wish this functionality of pressing a button to load ajax data had a clear explanation on the docs.

    Since you are using jQuery's ajax instead of Datatables ajax I would recommend reading some tutorials like this:
    https://howtodoinjava.com/jquery/jquery-ajax-tutorial/

    I updated the example with an input:
    http://live.datatables.net/huyexejo/122/edit

    You can look at the developer tools > network > header and see the value in the input is being sent as a parameter to the server. The server is ignoring and returning all the data. I also added some debug output to see the code execution steps.

    Kevin

This discussion has been closed.