How to alert if ajax response is empty

How to alert if ajax response is empty

dctootalldctootall Posts: 5Questions: 2Answers: 0

I had such good luck last time that I thought I'd try again.

I'm working on trying to add some extra validation and /or errors into my page. While it is unlikely, there is a fringe case where the Ajax query that is used to populate my datatable could return nothing. ( "[]" ). In such cases this results in the table displaying a "No data in table" message. If possible, I would like to be able to add an extra validation step that will allow me to pop an alert message to inform the user exactly what situation would've caused the no data .

I'm having a hard time figuring out where I could throw a validation check in to check the ajax response. there is no success function in the datatables ajax, and if I add one it breaks the page load. If I try adding it elsewhere in the initialization it doesn't work either or causes syntax errors.

This makes me believe that I would need to check for a no data situation once the datatable is completely initialized, but I'm not sure what the best way to do such a check is. Any help would definately be appreciated. :smile:

This question has an accepted answers - jump to answer

Answers

  • dctootalldctootall Posts: 5Questions: 2Answers: 0

    I figured out how to generate the alert. It required a slight change in my thinking on how it needed to be done, but I've verified that this gets the result I was looking for.

        $('#dataTable').on( 'draw.dt', function(){
             if (! table.data().any() ) {
                    alert( 'Empty Table' ); }
            });
    

    Essentially I need to create a listener that ran after the datatable completed it's draw, and then checked for any data within the datatable, instead of checking the response of the ajax query directly. The above code is placed with my other listeners outside of the datatable init. It then run after the initial init/draw is completed (draw.dt), and will run a if query to check for any data within the datatable api.

  • ApezdrApezdr Posts: 43Questions: 4Answers: 5
    Answer ✓

    Great catch.

This discussion has been closed.