I need help to update stateLoadCallback to new method

I need help to update stateLoadCallback to new method

lenamtllenamtl Posts: 265Questions: 65Answers: 1

Hi,

I'm trying to update from

I need help to update my function to work without async false

Actual code

stateLoadCallback: function(settings) {                    

        var table49 = "allquotes";
        var o;

        $.ajax( {
            "url": "ASEngine/ASAjax.php?action=load",
            "data":{ "user_id":"<?php echo $userId; ?>", "action" : "loadDataTable", "tablename" : table49},
            "async": false, // problem
            "type": "POST",
            "success": function (json) {
                            o = json;
            }
        });

            if(o){
                return JSON.parse(o);
            }else{

        }
    }

Newer method

            stateLoadCallback: function (settings, callback) {
                $.ajax( {
                    url: '/state_load',
                    async: false,
                    dataType: 'json',
                    success: function (json) {
                        callback( json );
                    }
                } );
            }

This question has an accepted answers - jump to answer

Answers

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1

    There is no more var o;

    So I'm wondering how to check if there is a value and parse it.

     if(o){
                    return JSON.parse(o);
                }else{
    
            }
    

    Thanks

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

    It looks like you asked the same question in this thread. Please only post questions once to avoid wasting people's time.

    Colin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1

    Hi @Colin,

    This is not the same question.
    The first question was about a bug found in old version and I'm looking for a fix.

    This new question is about how to migrate to the new version.
    I have not found documentation about the callback and how to work with.
    In the actual case, there is no more var o, there is no information on how it was replaced?

    I agree the latest comment from the first question should go under the newer question, my bald. I also understand the async and the if... problem.
    I could no found documentation on how callback replace the var o, the example is not clear how to parse the result.

    If you read all my questions, a lot are related to real bugs and the last thing I want to do is to waist your time I just want to help and understand so I can make a better use of Datatables.

    I highly recomment Datatables on every forum I use.

    I'm really sorry if you waisted your time with my questions, I always appreciate your help.

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925

    I don't think there is anything you need to do with it. If you want to process the retrieved state then use the stateLoadParams which will run after the ajax response in the stateLoadCallback.

    I updated Allan's example from the other thread you mentioned to demonstrate this:
    http://live.datatables.net/hiviroqe/1/edit

    If this doesn't help then please describe specifically what you are trying to do so we can help.

    Kevin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1

    Hi,

    I see in your example that you have a return {}; which is not present on the example.
    Also I added dataType which was not present from my first function.

    So I endup with this:

    stateLoadCallback: function(settings, callback) {                       
    
    var table52 = "rejectedcontacts";
    
    $.ajax( {
        "url": "ASEngine/ASAjax.php?action=load",
        "data":{ "user_id":"<?php echo $userId; ?>", "action" : "loadDataTable", "tablename" : table52},
        "dataType": "json",
        "type": "POST",
        "success": function (json) {
                 callback( json );
        }                           
        });
    
        return {};
    
    },
    

    Some of the settings are loaded ok like search and ordering but not ColReoder (this not loaded from the saved value).

    The main problem I have is it duplicate the button row, search field, show x field and the footer is also duplicated showing twice the navigation bar ...

    If I console.log stateLoadParams
    The old version gave me an object and the new version gave me the result I usually got from the stateLoadCallback when console.log(o);

    This is confusing... so how could I load with stateLoad Params from stateLoadCallback?

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925

    Some of the settings are loaded ok like search and ordering but not ColReoder (this not loaded from the saved value).

    The main problem I have is it duplicate the button row, search field, show x field and the footer is also duplicated showing twice the navigation bar ...

    In the example I posted the same thing happens with some duplicated elements. I removed the return {}; and now it looks correct. In the docs it states:

    If the data will be loaded asynchronously (e.g. via Ajax), undefined should be returned (just don't use a return statement!) and the callback function called when the state has been loaded

    Allan's example had the return {}; which it probably shouldn't have.

    I also added the colReorder JS and CSS to allow for reordering.

    the updated example seems to be working correctly now and updating the reordered columns.

    so how could I load with stateLoad Params from stateLoadCallback?

    The callback parameter is used to call statLoadParams. It passes in the JSON response. You don't need to do anything.

    Kevin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1
    edited August 2020

    Hi,

    Thanks for the clarification, this seems to work better now.

    The only problem I still have is when no settings yet, it break the code.
    (No error in console but it's not loading my buttons)
    Is there anything from the new Datatables version that hide errors?

    The case
    Let say there is no settings saved yet
    This should not load the setting from the save but load the table as it set by default in the JS.

    If the user change the settings then now we save the settings and these could be loaded from the save.

    In my previous code I was checking if o return the settings else do nothing...
    How can I verify this with the new function as it is not possible to return something from the stateLoadCallback...

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925
    edited August 2020

    The only problem I still have is when no settings yet, it break the code.

    I updated the test case to simulate an empty JSON response for both tables. I also added buttons to the first table. If the result is empty then the stateLoadParams does not run. See the example:
    http://live.datatables.net/datufaye/1/edit

    How can I verify this with the new function as it is not possible to return something from the

    What is returned from the Ajax request if there is no settings for the user? I guess you can check the json in the stateLoadCallback and if its empty use something like:
    callback( {} ).

    Can you update this example to show the problems you are having so we can help. I'm having a hard time understanding exactly what the problem is.

    Kevin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1

    which one is the good method as you are using both in your example
    callback( [] ); // Simulate empty settings
    callback( {} ); // Simulate empty settings

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1

    I'm saving the data like this in DB

    {"time":1598643708469,"start":0,"length":5,"order":[[8,"asc"]],"search":
    {"search":"","smart":true,"regex":false,"caseInsensitive":true},"columns":[{"visible":true,"search":
    {"search":"","smart":true,"regex":false,"caseInsensitive":true}},{"visible":true,"search":
    {"search":"","smart":true,"regex":false,"caseInsensitive":true}}],"ColReorder":
    [0,1,2],"naruto":"kurama","checkboxes":[]}
    

    should I use JSON.parse() for the result like before if result exist see the code posted in my question

    if so I don't know how to check if result and how to parsed it with the new function.

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925
    edited August 2020

    which one is the good method as you are using both in your example

    They both seem to work but since the normal response is an object I would suggest using an empty object, ie, {}.

    Go back to this example and you will see in the console log that in the stateLoadParams function the data is an object. You shouldn't need to parse it.

    Kevin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1
    edited August 2020

    Hi,

    I did more tests

    If you check the code from my question the stateLoadCallback ajax Post the tablename & user retreive from DB

    Case 1 = If there is no data in DB yet for that user&table, it Should load the default value from Datatables and it is Not and it's creating errors as not button appear, no ordeing icon etc = problem

    If I refresh the page now the default value get saved in DB = it's ok.

    Case 2 = Now let say I edit the DB entry and change the settings saved :

    {"time":1598882194871 ... }

    to this

    { }

    It load the default settings from datatables (not from DB) = it's ok.

    Case 3 Now If I edit the DB value and save it as empty
    { }
    to this (empty) no curly bracket

    Now I have the same error like in Case 1 = problem

    So the result of callback( json ); is causing the problem when no data in DB.

    I don't know what I could console.log to get more info as when there is no data nothing is log from stateLoadParams for all 3 cases..

    With the old method (old datatables version) I have not this issue because I was able to check if there is value for that user & table and parsing the value only if there is value and I don't know how I could do that with the new version / method

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925

    Case 1 = If there is no data in DB yet for that user&table,

    What exactly is returned in this case?

    Can't you just use the same if condition with the json variable in stateLoadCallback and call the callback method with an empty dataset, ie callback( {} );?

    Kevin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1
    edited August 2020

    it return nothing visible from the console into stateLoadParams

    But it's returning an invisible error has it brake the table.

    I don't know why but since the new Datatables version there is no more error reporting into the console like before.

    How would you do that ?
    Can't you just use the same if condition with the json variable in stateLoadCallback and call the callback method with an empty dataset, ie callback( {} );

    There is no var o like before and the stateLoadCallback load the stateLoadParams automatically...

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925

    Use the network inspector to see the XHR response from the stateLoadCallback. What is the value?

    Use console.log(json); in the stateLoadCallback. What is the output?

    Kevin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1
    edited August 2020

    For XHR response: I got jQuery-2.2.0.min.js:4 XHR finished loading: POST...

    For StateLoadCallback log : I see nothing into the console
    If I refresh the page I see the settings

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1

    When no data saved yet I have

    XHR finished loading: POST "http://localhost/....../ASAjax.php?action=load"
    XHR finished loading: POST "http://localhost/....../ASAjax.php?action=save"
    XHR finished loading: POST "http://localhost/....../ASAjax.php?action=save"

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925

    For XHR response: I got jQuery-2.2.0.min.js:4 XHR finished loading: POST...

    Did you look at the Response tab to see what is returned?

    I see nothing into the console

    Ok, then try console.log(typeof json); to see what it is. Then create an if statement to handle the empty json. Something like this maybe?

    if ( json ) {
      callback( json );
    } else {
      callback( {} );
    }
    

    Kevin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1
    edited August 2020

    Hi,

    Result tab = no response available for the POST.
    If I refresh I can see the response

    for the type = object

    The (json) if statement you provide does not work ...

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925

    The if (json) if statement you provide does not work ...

    What is not working?

    Does it work when there are saved settings?

    If there are no saved settings does the if statement follow the expected path and use callback( {} )?

    Maybe you need to change the if statement test to something that tests for an empty object. See some options in this SO thread.

    Kevin

  • lenamtllenamtl Posts: 265Questions: 65Answers: 1
    edited August 2020

    What I mean is that the if statement does not catch my result as empty, probably because my server side code send something even if empty if data does not exist...
    Yes it worked with there are save settings.

    I have tried a few way to check if empty object but it does not catch it on page load only when I refresh the page.

    Maybe the way would be to find is the result is undefined, I could not catch that too.

    Maybe @Allan can suggest a way to do it...

    Server side solution :
    What I did is I changed my server side code (PHP) so before loading the value, it check if exist in DB then if it's not existing in DB It send { } as result and if it exists it send the settings. It is probably not the faster method but it's does the job for now.

    Thanks a lot for your patience, I really appreciate your help

  • kthorngrenkthorngren Posts: 21,184Questions: 26Answers: 4,925
    Answer ✓

    it check if exist in DB then if it's not existing in DB It send { } as result and if it exists it send the settings.

    Sending an empty object is what I would do. This way the data structure is consistent and you probably won't need the if statement in the stateLoadCallback.

    Kevin

  • rf1234rf1234 Posts: 2,950Questions: 87Answers: 416

    Thanks, that helped me to get my solution up and running quickly.

    JSON encoding, decoding, parsing etc. is kind of difficult though. If I find nothing on the server I return a string that contains the javascript notation of an empty object which is completely meaningless in PHP. Weird, but works.

    My Javascript:

    stateLoadCallback: function(settings, callback) {
        if ( stateSave ) {
            $.ajax({
                type: "POST",
                url: 'actions.php?action=retrieveState',
                data: {
                    userId:     currentUserId,
                    dataTable:  "subTable",
                    webPage:    webPage
                },
                dataType: "json",
                success: function (json) {
                    callback(JSON.parse(json));
                }
            });
        }
    },
    

    My PHP:

    $dbh->query('SELECT `values`
                   FROM saved_state 
                  WHERE user_id         = :userId
                    AND data_table      = :dataTable
                    AND web_page        = :webPage');  
    $dbh->bind(':userId',       $userId);
    $dbh->bind(':dataTable',    $dataTable);
    $dbh->bind(':webPage',      $webPage);
    $row = $dbh->singleAssoc(); // a one-dimensional array is returned SINGLE
    if ( (bool)$dbh->rowCount() ) {
        return json_encode($row["values"]);
    }
    return json_encode( '{}' );
    
Sign In or Register to comment.