stateSaveCallback & stateLoadCallback server-side issue RESOLVED!

stateSaveCallback & stateLoadCallback server-side issue RESOLVED!

Alan14Alan14 Posts: 1Questions: 1Answers: 0

I've seen several people post issues regarding stateSaveCallback and stateLoadCallback passing data, but their stateLoadCallback was not updating their list. I'm posting my solution once here instead in each of the other posts. (This post got me pointed in the right direction: https://datatables.net/forums/discussion/28796/)

The issue is that the JSON that is sent to the server needs to be modified. The quotes surrounding numbers AND boolean values need to removed before saving the JSON to your database. Here's a simplified version of what I do using PHP and jquery:

in my js file:

stateSaveCallback: function( settings, stateData ) {
    $.ajax({
        url: 'stateSave.php',
        method: 'POST',
        data: {
            id: $('input[name=listid').val(),
            state: stateData
        },
        dataType: 'json'
    })
},
stateLoadCallback: function( settings ) {
    var o;
    $.ajax({
        url: 'stateLoad.php?id=' + $('input[name=listid').val(),
        async: false,
        dataType: 'json',
        success: function( json ) {
            o = json;
        }
    });
    return o;
}

In my stateSave.php file:

# 1. encode json with quotes removed from numbers
$stateJsonString = json_encode( $_POST['state'], JSON_NUMERIC_CHECK );

# 2. remove quotes from boolean values
$stateJsonString = str_replace( ['"true"', '"false"'], ['true', 'false'], $stateJsonString );

# 3. save $stateJsonString in database

In my stateLoad.php file:

# 1. retrieve stateJsonString from database
# 2. echo the string
header( 'Content-Type: application/json; charset=utf-8' );
echo $stateJsonString;

stateLoadCallback now processes the json correctly!

Answers

  • ajay2529ajay2529 Posts: 7Questions: 1Answers: 0

    how to solve column visibility not working in stateload from database

  • colincolin Posts: 15,118Questions: 1Answers: 2,583

    Hi @ajay2529 ,

    That's a different issue to the thread posted here - this thread was a helpful example on how to save the state remotely via Ajax. If your issue is still a problem for you, please create a new thread.

    Cheers,

    Colin

  • ajay2529ajay2529 Posts: 7Questions: 1Answers: 0

    thanks for your answer

  • davide_paloschidavide_paloschi Posts: 1Questions: 0Answers: 0

    You saved my life. Great great great work

  • jsosajsosa Posts: 14Questions: 4Answers: 0

    Alan, thanks for this answer. I spent a long time trying to figure out why column visibility was not working on load. I read on this post that the strings need the original data type instead of using quotation marks. But the stateLoadCallback example given in documentation wasn't helping.

    I ended up using JSON.stringify(data) in the ajax call for stateSaveCallback and stored the posted string in the database.

This discussion has been closed.