How to stop page from refreshing when submitting AJAX through btn click?

How to stop page from refreshing when submitting AJAX through btn click?

dataphpmysqldataphpmysql Posts: 65Questions: 17Answers: 0

Hello.

So what I want 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 the search button. That's all I'm trying to do.

But right now how I have the code (which syntax I found online) is the following. If the user clicks the button, the page refreshes and ignores the inputs. Then after clicking again it works. So on so forth.

Here is the ajax call (perhaps the 'draw' is the issue?):

    <script>
        $("#btnSearch").on("click", function (event) {
            var searchData = {
                "testID": $('input[name=testID]').val()
            };
            $.ajax({
                Type: 'GET',
                url: 'https://insertaddresshereamazonaws.com/prod',
                data: searchData,
                dataSrc: ''
            }).done(function (result) {
                table.clear().draw();
                table.rows.add(result).draw();
            }).fail(function (jqXHR, textStatus, errorThrown) {
                // needs to implement if it fails
            });
        })
    </script>

And here is the regular datatable code although I don't have any issues with it so I don't think the problem is here:

<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 = $('#dtBasicExample').DataTable({
            columns: [
                {
                    "className": 'details-control',
                    "orderable": false,
                    "data": null,
                    "defaultContent": ''
                },
                { "data": "example" },
            ]
        });

        $('#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>

Any idea how to fix this and stop the page from refreshing when initially clicking the button?
Thanks.

Answers

  • kthorngrenkthorngren Posts: 20,145Questions: 26Answers: 4,736
    edited September 2019

    If the user clicks the button, the page refreshes and ignores the inputs. Then after clicking again it works

    Are you saying that the searchData parameter is not sent in the ajax request?

    Not sure I understand the exact problem but it sounds like you are expecting the $('input[name=testID]').val() value to be sent to the server and the server responds with the appropriate data based on the input. Is the problem that the server isn't returning the correct data?

    I would start be looking at the browser's developer tools to see what is sent in the request and the corresponding response. The troubleshooting steps in this technote will show you how to do this.
    https://datatables.net/manual/tech-notes/1

    You are using jQuery ajax() not Datatables ajax option. jQuery ajax doesn't have the option dataSrc so you can remove that line.

    Its been awhile sinceI've used the .done() callback. You may need to use result = JSON.parse(result) to parse the JSON response into a Javascript object. You can use console.log(typeof result); to determine if its a JSON string or an object.

    Here is you ajax call with some changes and comments:

            $.ajax({
                Type: 'GET',
                url: 'https://insertaddresshereamazonaws.com/prod',
                data: searchData,
                dataSrc: ''   // remove this, its not a jquery option
            }).done(function (result) {
                console.log(typeof result);  // See what the data type is
                result = JSON.parse(result)  // Use this if the type is string
                table.clear().draw();   // You can remove this draw() as it is a wasted call since you use it in the next line
                table.rows.add(result).draw();
            }).fail(function (jqXHR, textStatus, errorThrown) {
                // needs to implement if it fails
            });
    

    If this doesn't help then please post a link to your page or a test case replicating the issue. It will be hard to offer specific suggestions without seeing the problem happen.
    https://datatables.net/manual/tech-notes/10#How-to-provide-a-test-case

    Kevin

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

    Thanks for the response. So the issue is that whenever I click the button, the page refreshes, nothing is sent o the server. Then, after I click again, the data is received successfully.

    After two clicks I'm able to receive the data so I don't think there's any issues with parsing the data type or receiving it. I'm guessing the issue comes from "draw". Anyhow, this is an old syntax I found online, I'm gonna open a new question to ask for what I'm looking for since troubleshooting this code might not even lead to the desire outcome; which is simply to activate the ajax call after clicking a button, instead of document.ready.

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

    So the issue is that whenever I click the button, the page refreshes, nothing is sent o the server. Then, after I click again, the data is received successfully.

    I would put console.log debug statements in your button click event to see what is happening. If you click the button and the ajax request isn't sent to the server then that is outside of Datatables realm of control. The only place in your event handler that would refresh the page is in the .done() callback which I wouldn't expect to run unless there ajax request was sent to the server and a response received. You can verify using console.log statements in side .done().

    Do you have another event handler on your page for that button?

    Kevin

This discussion has been closed.