save the SearchPane selection to a database

save the SearchPane selection to a database

TnavarroTnavarro Posts: 5Questions: 1Answers: 0

I have a table with multiple columns. I wanted to know if the selection made by the user through SearchPane can be saved in the database so that later any user could reload the same saved selection. Please if someone could help me with some code or some guide

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 13,816Questions: 25Answers: 3,252
    Answer ✓

    One option is to use stateSave, like this example. You can use stateSaveCallback to define where to save the state.

    Kevin

  • TnavarroTnavarro Posts: 5Questions: 1Answers: 0
    edited September 18

    You will have an example how to save the stateSave with the **stateSaveCallback **function, I was reading the documentation and it was not very clear to me

  • colincolin Posts: 12,657Questions: 0Answers: 2,163

    The example on the reference page, stateSaveCallback, demonstrates how you would send that data to the server. Your server-side script, whichever tech you use, would then write to the DB. stateLoadCallback would then be used to retrieve that from the DB on table initialisation,

    Colin

  • colincolin Posts: 12,657Questions: 0Answers: 2,163

    p.s. we're close to release another extension, StateRestore, which is a lot more powerful, and allows multiple states to be stored. This should be released in the coming month.

    Colin

  • TnavarroTnavarro Posts: 5Questions: 1Answers: 0

    @colin and @kthorngren I've been trying to pass the data like they told me with stateSaveCallback first, but since I'm new to datatables I don't understand much. When trying to pass "data" through ajax it gives me the following error and I don't understand it. Also I do not understand if I must occupy any extension in the php controller to be able to receive the data that I am sending through ajax in my controller and send it to my database.
    Below I leave an image of the error that it gives me.

    You will have a tutorial or steps to follow to achieve it (I have seen many examples in the forum but they are not complete), please it is very important to me

  • colincolin Posts: 12,657Questions: 0Answers: 2,163

    It looks like that's an error coming back from your server, from the filtrar at line 382. Have you checked the network tab on the brower's dev tools to see what's being sent and received when this request is made?

    Colin

  • TnavarroTnavarro Posts: 5Questions: 1Answers: 0

    I just reviewed, well I don't understand much (I'll leave you the image 1
    ). but the idea was to send what contains "data" to my controller in order to send it to my database, so in url I put "filterController" this is my controller. on the other hand I was trying to use the "stateLoadCallBack" to see if it worked with an X example and it worked (it returns a JSON).
    what I don't understand is why it doesn't go through the ajax "success" function, it throws me the error (filter: 453 message =: [object Object], text status =: parsererror, error thrown: = SyntaxError: Unexpected token <in JSON at position 0)

    Image 1

    Image 2

    another alternative that I think is that actually if I get something through ajax, but I don't know how to handle it in the controller, but I think it's the least likely alternative given the error that ajax throws at me

    This is what the "POST" method returns

    and this is how i am trying to display the content

    Excuse my bad english :(

  • allanallan Posts: 54,714Questions: 1Answers: 8,560 Site admin

    This is what the "POST" method returns

    That is showing the request and response headers. If you click the "Response" tab in that view, it will show what is sent back. The error suggests that it is not valid JSON.

    Can you show me your controller for getting the state (I presume start_save is for saving a state, but it doesn't appear to be doing that?) and also your stateLoadCallback function?

    Allan

  • TnavarroTnavarro Posts: 5Questions: 1Answers: 0

    hello allan and thank you very much for your answer. today I was looking at some posts in the forum and tried to use some of them but I still can't send data using the "stateSaveCallback" function, this was one of the posts that caught my attention the most:
    https://datatables.net/forums/discussion/42622/statesavecallback-stateloadcallback-server-side-issue-resolved

    I tried to apply it to my controller and script but it didn't work, specifically it told me that

    **here is my code with all datatables: **

    $(document).ready(function() {

                var table = $('#example').DataTable({
    
                    "stateSave": true,
    
                    language: {
                        "url": "https://cdn.datatables.net/plug-ins/1.11.3/i18n/es_es.json"
                    },
    
                    // Scrolling Tabla
                    "scrollY": true, // Constrain the DataTable to the given height
                    "deferRender": true, // Elements will be created only when the are required
                    "scroller": true, // Enable vertical scrolling in DataTables
                    "scrollX": true, // Scroll horizontal
                    "colReorder": true, // Column reordering
                    buttons: [{
                            extend: 'copy',
                            text: '<i class="fas fa-copy"></i>',
                            titleAttr: 'Copiar',
                            className: 'btn btn-warning'
                        },
                        {
                            extend: 'excel',
                            text: '<i class="fas fa-file-excel"></i>',
                            titleAttr: 'Exportar Excel',
                            className: 'btn btn-success'
                        },
                        {
                            extend: 'pdf',
                            text: '<i class="fas fa-file-pdf"></i>',
                            titleAttr: 'Exportar PDF',
                            className: 'btn btn-danger'
                        },
                        {
                            extend: 'csv',
                            text: '<i class="fas fa-file-csv"></i>',
                            titleAttr: 'Exportar CSV',
                            className: 'btn btn-success'
                        },
                        {
                            extend: 'print',
                            text: '<i class="fas fa-print"></i>',
                            titleAttr: 'Imprimir',
                            className: 'btn btn-info'
                        },
                        {
                            extend: 'colvis',
                            text: '<i class="fas fa-print"></i>',
                            className: 'btn btn-info',
                            titleAttr: 'Imprimir',
                            columnText: function ( dt, idx, title ) {
                            return (idx+1)+': '+title;}
                         }      
    
                    ],
    
                    searchPanes: {
                        cascadePanes: true,
                        dtOpts: {
                            dom: 'tp',
                            paging: 'true',
                            pagingType: 'simple',
                            searching: true,
                            viewTotal: true
                        }
                    },
                    columnDefs: [{
                        searchPanes: {
                            show: true
    
                        },
                        targets: []
                    }],
                    dom: 'PBf;lfrtip',
                     "drawCallback": function( settings ) {
                        var api = new $.fn.dataTable.Api( settings );
                        // Output the data for the visible rows to the browser's console
                        // You might do something more useful with it!
                        console.log( api.rows( {page:'current'} ).data() );
                     },
                    // Falta agregar un if si esta pulsado el boton guardar que se active este metodo.
                    "stateSaveCallback": function(settings, data) {
                        // Send an Ajax request to the server with the state object
    
                        //console.log("Aqui esta la data: " + data.searchPanes)
                        $.ajax({
                            "url": "filtrar",
                            "data":  {'data': data},
                            "dataType": "json",
                            "type": "POST",
                            "success": function() {
                                console.log('PASOOO! -> save' + data.time + 'data search' ); // <--- Nunca pasa por aca
                            },
                            error: function(data, textStatus, errorThrown) {
                                console.log('message=:' + data + ', text status=:' + textStatus + ', error thrown:=' + errorThrown);
                            }
                        });
                    },
                    // Falta agregar un if si esta pulsado el boton cargar filtros que se active este metodo.
                    stateLoadCallback: function(settings, callback) {
                        $.ajax({
                            url: 'http://blakbit.com/dt_test.php?id=example&load',
                            dataType: 'json',
                            //async : false,
                            success: function(json) {
                                console.log('JSON ---->:', json)
                                callback(json);
                            }
                        });
                    }
                });
            });
    

    this is the method by which I intend to send the data to my database

      public function state_save() {    
    
               // First attempt
    
        $valorajax=[];
    
        $valor = $this->request->getPost($valorajax);
    
        var_dump($valor);
    
        // second attempt 
    
        echo "Aqui el Json ->".json_encode($_POST);
    
        //third attempt 
    
        // Recibo lo enviado por ajax 
        $stateJsonString = json_encode( $_POST['data'], JSON_NUMERIC_CHECK );
        $stateJsonString = str_replace( ['"true"', '"false"'], ['true', 'false'], $stateJsonString );
    }
    

    From what I saw I don't need to import anything to my controller or do I need to in order to process the data?

    **Here is what I get by console and network
    **

  • allanallan Posts: 54,714Questions: 1Answers: 8,560 Site admin

    Can you give me a link to your page showing the issue please? If you can't post it here in the public forum, drop it to me via a PM by clicking my name above and then the Send message button.

    Allan

Sign In or Register to comment.