Custom form and AJAX search API

Custom form and AJAX search API

FedericoVFedericoV Posts: 35Questions: 9Answers: 0

I'm trying to add a custom input search form into my Datatables and I'd like to keep the Datatables search API features...for example keeping the rsult in cookies...so if the user goes out and in into the page he'll get the previous search result ( this could be useful if the datatables rows include link to detailed page about each row..so the user could go to the details page and get back to research)

For what I can read into the following pages: https://datatables.net/reference/api/column().search() and https://datatables.net/reference/api/search()

I can set the custom input to be linked to search and draw Datatables functions....but I don't understand if and how this features could be related to AJAJ query.

Thanks a lot for any hint or feedback. Right now my Datatables is available here: https://gavs.it/rmidev/domestic

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922

    Looks like you are sending the values from the inputs as ajax.data parameters. Datatables doesn't know anything about this since you aren't using the Datataables search API's. However you can use stateSaveParams to save the values of the inputs. Then use stateLoadParams to get the values and populate the inputs.

    Kevin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Thanks a lot Kevin, sounds interesting. Sorry, can I ask if you can point me to a detailed example? The linked page are quite hard to understand for me...I'm not an experienced programmer.
    Thanks a lot.

  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922

    Here is an example:
    http://live.datatables.net/hapumoyo/1/edit

    The actual Ajax requests sends the parameter bbut the server script doesn't pay attention to it. But the example should show you the flow of everything through console.log statements.

    Kevin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Invaluable help Kevin, really appreciated. Helps me a lot to learn and understand Datatables.
    I'll try the code and report you back.

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0
    edited April 2020

    So,
    the new code works fine for research...but the searched text is not highlighted in table nor table keep state of searched data if I move outside the page then get back to Datatable...sounds really weird...
    You can see th esult at the following page https://gavs.it/rmidev/domestic
    In the page at the link above I've reactivated standard search form for comparison

  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922

    but the searched text is not highlighted in table

    Looks like you commented out the code to highlight the table.

    nor table keep state of searched data if I move outside the page then get back to Datatable

    You can trigger a state save using state.save() in your keyup event.

    Kevin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Hi Kevin,
    I've commented that line because it ever didn't worked. I've uncommented it just for test ( you can check it at my link above ) and it doesn't work.

    I've added the state.save code to the keyup event, so the related code is now:

    $('#searchRegistration').keyup(function () {
        console.log('Redrawing table, searching for', $(this).val());
        table.draw();
        table.state.save();
        if ($(this).val() == '') {
            //Check to see if there is any text entered
            // If there is no text within the input ten disable the button
            $('.query-btn').prop('disabled', true);
        } else {
            //If there is text in the input, then enable the button
            $('.query-btn').prop('disabled', false);
        }
    });
    

    but the state save doesn't work...just tested it as follow:
    - search the number 1 in Search Registration field. The Datatable redrawn show just the related row.
    - click on the 1 anchor data
    - get to the details page
    - getting back I see the whole list.

    Pagination, instead, works fine...but I think this is because pagination is not custom and uses standard Datatables function.

    I'm starting to think that I have to give up with the Datatables features with custom search...this is a pity

  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922
    Answer ✓

    Ok, the problem is you have the stateLoadParams and stateSaveParams inside the ajax option. You won't need the state.save() API but will need to move these outside the ajax option.

                    ajax: {
                        url: "https://gavs.it/rmidev/domestic_list",
                        type: "POST",
                        "data": function ( d ) {
                            d.csrf_test_name = token_hash;
                            // Read values
                            var registration = $('#searchRegistration').val();
                            var model = $('#searchModel').val();
                            d.registration = registration;
                            d.model = model;
                            //var name = $('#searchByName').val();
                            //var val = $('#save-text').val();
                            console.log('Setting custom serverside search value:', registration);
                            console.log('Setting custom serverside search value:', model);
                            //d.my_search = val;
    
                            // Append to data
                            //data.searchByGender = gender;
                            //data.searchByName = name;
                        },
                        "stateLoadParams": function (settings, data) {
                           console.log("stateLoadParams");
                           console.log(data);
                           $('#searchRegistration').val(data.mm);
                           $('#searchModel').val(data.tipo);
                        },
                        "stateSaveParams": function (settings, data) {
                          console.log("stateSaveParams");
                          data.mm = $('#searchRegistration').val();
                          data.tipo = $('#searchModel').val();
                          console.log(data);
                        },
                        "dataSrc": function ( json ) {
                            token_hash = json['csrf_test_name'];
                            //return json.data;
                            //var return_data = new Array();
                            for(var i=0; i< json.data.length; i++){
                                /*
                                return_data.push({
                                    'mm': '<a href="' + controller_url + '/data/' + json.data[i].id + '">' + json.data[i].mm + '</a>',
                                    'ditta': json.data[i].ditta,
                                    'tipo': json.data[i].tipo,
                                    'motori': json.data[i].motori,
                                    'nc': json.data[i].nc,
                                })
                                */
                                json.data[i].mm = '<a href="' + controller_url + '/data/' + json.data[i].id + '">' + json.data[i].mm + '</a>';
                            }
                            //return return_data;
                            return json.data;
                        }
                    },
    

    Looks like the highlighting code is still commented out:

                /*
                var table = $('#table').DataTable();
                
                table.on( 'draw', function () {
                    var body = $( table.table().body() );
     
                    body.unhighlight();
                    body.highlight( table.search() );  
                } );
    
                */
    

    Kevin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Silly me...sorry Kevin, I didn't read your code in example link. My apologize.
    The state now works fine...still highlight doesn't work ( and I'm sure it's again my fault), but I'm noy able to find the issue.

    Finally I uncommented the correct code ( hopefully )...but maybe I'm missing something...

    table.on( 'draw', function () {
        var body = $( table.table().body() );
     
        body.unhighlight();
        body.highlight( table.search() ); 
    } );
    
  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Keep posting...even if my replies doesn't appear or are waiting for approval...don't understand why...in any case...
    I tried to edit the highligth code as follow...still no luck

    table.on( 'draw', function () {
           var body = $( table.table().body() );
     
            body.unhighlight();
            body.highlight($("#searchRegistration").val());
            body.highlight($("#searchModel").val()); 
    } );
    

    Thanks again for any hint and help

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Update:...seems to be fixed but I'm not sure the correct way to do that.

    Modified the highlight code as follow:

    function spotlight()
     {
        table.on( 'draw', function () {
        var body = $( table.table().body() );
         
        body.unhighlight();
        body.highlight($("#searchRegistration").val());
        body.highlight($("#searchModel").val()); 
        } );
    }
    

    Additional, I call the spotlight function in custom input field keyup event, after table draw...like follow:

    $('#searchRegistration').keyup(function () {
         table.draw();
         spotlight();
    });
    

    Could I make it better?
    Thanks a lot

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

    these messages were caught in the spam filter - I just released them, but it looks like this thread was already resolved by Kevin's last reply.

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Thanks a lot colin. I'm just interested now in Kevin opinion about my latest edited code.
    Support at the top in Datatables forum...a big thanks

  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922

    Take it out of the function. You want it to setup an event listener when the page loads, like this:

        table.on( 'draw', function () {
        var body = $( table.table().body() );
          
        body.unhighlight();
        body.highlight($("#searchRegistration").val());
        body.highlight($("#searchModel").val());
        } );
    

    In your test case you have:

                $("#btnSubmit").click(function(){
                    table.draw();
                    spotlight();
                    //$('#table').DataTable().draw();
                });
    

    Which executes the function when clicking the "Search" button. When I click the search button it does highlight.

    But it needs to be outside of a function otherwise you are going to create an additional event each time the button is clicked.

    Kevin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Thanks for your hint Kevin.
    I've get rid of the function ...but now the searched data are not highlighted.
    I've modified the script so, right now, the Datatables is drawn when I click on submit button ( since I keep getting error if I type too fast in the search data...so I'd like to avoid those error in public pages ); in any case I have the same issue with highlight data.

    The weird things is that:
    - I type the required data in the search form, click on Search button. Datatable correctly re-drawn with just the searched ( but not highlighted ) data
    - if I click on the link in table to get the detailed page, and get back to Datatables list, I see the searched data highlighted....this getting me crazy

  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922

    You have:

            table.on( 'draw', function() {
                    var body = $( table.table().body());
                    body.unhighlight();
                    body.highlight($("#searchRegistration").val());
                    body.highlight($("#searchModel").val()); 
                });
    

    Its first highlighting based on this body.highlight($("#searchRegistration").val());. then its highlighting based on this body.highlight($("#searchRegistration").val());. Using the debugger I can see that after clicking search the first one highlights but then the second clears the highlights. Comment out the second to see it work.

    Take a look at the highlight.jst docs for examples of how to use multiple values to highlight.

    Kevin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Again into the spam spider...
    The code below seems not working at all...no searched text is now highlight :(

    table.on( 'draw', function() {
         var body = $( table.table().body());
         body.unhighlight();
         body.highlight([$("#searchRegistration").val()], [$("#searchModel").val()]); 
    });
    

    Thanks

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Looking into the linked highlight.jst file, I've edited the code into:

    table.on( 'draw', function() {
           var body = $( table.table().body());
            body.unhighlight();
            body.highlight([$("#searchRegistration").val()], [$("#searchModel").val()]);
     });
    

    This way, the first searched data ( registration) is highlighted just after page re-load, while the second searched data ( model ) is never highlighted, even after page re-load.

    Can I ask what debugger are you using, Kevin? I guess you are referring to the Chrome tool....which section or tab?

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Kevin...you are a master hero!
    Silly me, my fault about the state Option inside ajax call, I didn't carefully your example and code...my apologize.
    So, the page, now, keep the state.

    About the highlight, I have ( hopefully ), now uncommented the right piece of code..so the related code now is:

    table.on( 'draw', function () {
            var body = $( table.table().body() );
     
            body.unhighlight();
            body.highlight( table.search() );  
    } );
    

    The searched valkue still are not uncommented....I'm sure it's again my fault...damn...really sorry...I can't figure out what my silly brain doesn't realize is missing.

    PS: can I pay a beer to you for all your support?

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

    yep, spam folder again, I released the messages, but suspect they're not needed - it seems like Kevin sorted you out anyways.

    Colin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Thanks Colin.
    Sorry ..but highlight doesn't work yet.

    I've edited the code according to the file linked by Keing..

    table.on( 'draw', function() {
         var body = $( table.table().body());
         body.unhighlight();
         body.highlight([$("#searchRegistration").val()], [$("#searchModel").val()]);
    });
    

    Now, first field search result is highlighted just when I reload the page...the second search field result...is never highlighted.
    Can I ask for some more hint? Honestly I'm getting lost... and the highlight feature looks useful for user experience...

    Thanks a lot guys

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Sorry Colin, again in spalm.
    If I could ask for more help to figure out the missing higlighted searched text?
    Still not working

  • kthorngrenkthorngren Posts: 21,171Questions: 26Answers: 4,922
    edited May 2020

    I aren't using the Datatables search API for this so body.highlight( table.search() ); won't work as it wont have the values from your input.

    This is from the docs:

     *   // search for and highlight more terms at once
     *   // so you can save some time on traversing DOM
     *   $('#content').highlight(['lorem', 'ipsum']);
     *   $('#content').highlight('lorem ipsum');
    

    Looks like you want to use values from two inputs. You will need to put both of those in an array to pass to highlight():
    $('#content').highlight( ['lorem', 'ipsum'] );

    The first input replaces 'lorem' and the second replaces 'ipsum'.

    I guess you are referring to the Chrome tool....which section or tab?

    I used break points in your code to see values at certain points. Checkout this tutorial.

    Kevin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Hi Kevin, this is what I did with the following code:

    table.on( 'draw', function() {
            var body = $( table.table().body());
            body.unhighlight();
            body.highlight([$("#searchRegistration").val()], [$("#searchModel").val()]);
     });
    

    But it doesn't work.
    I give up

    I just want to thanks you for all your time, efforts and useful tips...in any case I've learnt so much

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

    I think @FedericoV 's last reply is duplicated - I released it from the spam filter, but looking at it, it seems a duplicate of an earlier comment. If that's not the case, please can you let us know.

    Colin

  • FedericoVFedericoV Posts: 35Questions: 9Answers: 0

    Hi Colin, the last reply is not a duplicate, thanks for posting.
    In any case I fixed the issue; thanks a lot for all your support and help.

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

    Excellent, glad all sorted, and apologies for the spam filter's dislike of you :)

    Colin

This discussion has been closed.