Full control over Ajax for both success and fail scenarios, separately

Full control over Ajax for both success and fail scenarios, separately

ForeOhForeForeOhFore Posts: 4Questions: 1Answers: 0
edited September 2020 in Free community support

I'm trying to make it so that I can have complete control over the Ajax call I am making using Datatables. This is so that I can customize success and error handling, independently of each other. I want to do more than just automatically send the data to the table on success and more than just simply manipulate the data and return it (doing those two things seems to be the extent of the use "dataSrc", but I could be wrong), and I want to do something different from having a pop-up alert window when there is an error (which is how Datatables exclusively seems to handle errors - I would prefer creating my own html based error messaging as opposed to having customers see and click a pop-up alert).

I was trying to use .on('xhr.dt', function ( e, settings, json, xhr ) {}) and .on('error.dt', function ( e, settings, techNote, message ) {}) in my code together, so that I can handle and customize success and error separately in separate blocks of code (since I plan on doing different actions on success than I do on fail), however, when there is an error, it always going inside of .on('xhr.dt', function ( e, settings, json, xhr ) {}). In reading about this, this is because xhr is triggered by both success and error conditions, so it will always going into .on('xhr.dt', function ( e, settings, json, xhr ) {}).

Again, I would like to handle success and error separately, so I saw in the documentation here and here where it says "Since 1.10.7, xhr can now return true to have DataTables not trigger the error event for cases where you've handled the error yourself now that xhr is triggered on error as well". However, neither page specify where I am supposed to return true from. From server side somehow...? Am I supposed to include it in ".on('xhr.dt', function ( e, settings, json, xhr ) {})"? Does the return true go into my JS code somewhere? Somewhere else? Can someone please give me an example or explain that?

I appreciate the library and think it is great; I just would like to find out how I can have more control over Ajax, for both success and error, and separately so that I can do separately things for both scenarios.

I tried to create a JSFiddle with some adjusted code, but it keeps giving a ""jQuery.Deferred exception: $(...).on(...).on(...).DataTable is not a function"" error, despite having added the Datables files as resources and it working for me on our own systems. So, I apologize, but I'll at least include my HTML and Javascript below.

Please help in anyway that you can. If I'm going about this all wrong, please point me to some examples or resources of being able to have full control over Ajax for both success and error separately with the ability run additional code inside of each. Thank you so much.

HTML:

<!DOCTYPE html>
<html>
    <head>
      <script>
        $(document).ready(function() 
             {
            init();
             });
        </script>
    </head>
    <body>
      <div style="max-width: 1400px; margin:auto">
            <br>
            <span id='successOrNotSpan'></span>
            <br>
            <table id='datatablesTable' class='no-wrap responsive display'></table>
      </div>
    </body>
</html>

Javascript:

// var test1 = null; // Test variable seen in dataSrc

function init()
{
    buildDatatablesTable();
}

function buildDatatablesTable() {
    var tableSelector = '#datatablesTable';

    var table = $(tableSelector)
    .on('xhr.dt', function ( e, settings, json, xhr ) {
        // Different things that I want to do if the Ajax call is successful, instead of just Datatables automatically putting the data into the table and moving on...
        $('#successOrNotSpan').html('Hey, it was successful!'); // Just as an example of what I'd want to be able to do
        doThings(); // Just as an example of what I'd want to be able to do
        doMoreThings(); // Just as an example of what I'd want to be able to do
    })    
    // If I do something to make the script error-out, it never goes inside of here. It always goes inside of the ".on('xhr.dt'...)". I want to handle success and error separately.
    .on('error.dt', function ( e, settings, techNote, message ) {
        test1 = "Oh no...";
        $('#successOrNotSpan').html('Uh-oh, that did not work...'); // Just as an example of what I'd want to be able to do
        doSomeDifferentStuff(); // Just as an example of what I'd want to be able to do
    })
    .DataTable({
        ajax: {
            url: '../SomeStuff/config.txt', // Contains a JSON object, with a "data" array of objects
        },
        // NOT using dataSrc because I can't pause code in Chrome Dev Tools within it and I don't seem to have access to variables I use in it
        //dataSrc: function ( json ) {
        //    test1 = json;
        //    return json.data;
        //},
        columns: [
            {
                title: 'Name',
                data: 'name',
            },
            {
                title: 'Rank',
                data: 'rank',
            },
            {
                title: 'Salary',
                data: 'salary',
            },
            {
                title: 'Number of Projects',
                data: 'projects',
            },
            { 
                title: 'Position', 
                data: 'extrainfo[0].position',
                className: 'none',
            },
            { 
                title: 'Years Worked, 
                data: 'extrainfo[0].yearsworked',
                className: 'none',
            },
        ],
        order           : [[0, 'asc']],
        select          : 'single',
        responsive      : true,
        scrollY         : 700,
        paging          : false,
        scrollCollapse  : true,
        language: {
            search: "",
            searchPlaceholder: "Search...",
            loadingRecords: "Loading...",
            processing:     "Processing...",
        },
    });
}

Answers

  • colincolin Posts: 15,240Questions: 1Answers: 2,599

    There's a lot going on there - we really would need to see it. This test case here could be used as a starting point if you're having problems creating one: http://live.datatables.net/yumufafo/1/edit

    Colin

  • ForeOhForeForeOhFore Posts: 4Questions: 1Answers: 0
    edited September 2020

    @colin, should I edit the code in that link you gave me, save it, and post it back here?

    In the meantime, does my question make sense? I'm really just looking for whatever combination of functions/code that will let me handle when there is a success or when there is an error, independently of each other and in separate code blocks, like success:/error: for AJAX or .done()/.fail() for jquery AJAX.

    Note: I'm aware of Datables not wanting you to override "success" itself, but I imagine there has to be something similar that you can do in Datatables to get a similar level of control and flexibility?

  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954

    The ajax docs state this:

    success - Must not be overridden as it is used internally in DataTables. To manipulate / transform the data returned by the server use ajax.dataSrc (above), or use ajax as a function (below).

    So you can use ajax.dataSrc in place fo success and the normal error function if you want.

    Kevin

  • ForeOhForeForeOhFore Posts: 4Questions: 1Answers: 0
    edited September 2020

    Hi, kthorngren.

    I tried dataSrc before, and it did process the data and put it into the table at least, but the code execution in Chrome Dev Tools would never stop at the breakpoints for the code that I put inside of dataSrc (that would make it difficult to debug the code). I also couldn't seem to reference even global variables that I created outside of dataSrc. I also tried calling some test functions in dataSrc, and that didn't seem to work.

    Perhaps I am missing something or you have a different experience using dataSrc? Thanks for your response.

  • kthorngrenkthorngren Posts: 21,341Questions: 26Answers: 4,954

    Not sure why you would have those problems. I updated Colin's test case with a global variable that is accessible within the ajax.dataSrc function. I assign it to a local variable which you can see in the debugger. For example:

    To be able to use the debugger with the Datatables JS BIN environment you need to use the Live Preview mode:
    http://live.datatables.net/yumufafo/2

    Kevin

  • ForeOhForeForeOhFore Posts: 4Questions: 1Answers: 0

    That's so interesting. Now, dataSrc is working for me as-expected. It legit wasn't stopping at break point, running functions, etc. Huh, seems something funky happened on my end or I was just trying out too many things at once and messed something up. Either way, it seems that a combo of "dataSrc:" and "error:" is pretty solid. It would still be nice to have access to all three "success" params - data, textStatus, and jqXHR - so I can do custom things based on, say, jqXHR.status or some other jqXHR property, for instance. That said, still solid enough to get me moving ahead and have my code working. Thank you so much, Kevin.

    I'm still curious about ".on('xhr.dt', function ( e, settings, json, xhr ) {})" and what the documentation in my first post said about how xhr can now return true to have DataTables not trigger the error event for cases where you've handled the error yourself now that xhr is triggered on error as well". I like that it would give me access to the xhr object. Do you know anything about that and how to get that solution working? Where and how is true supposed to be set and returned?

    Thanks again.

This discussion has been closed.