Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Datatables - how to pass search parameter in a url

I would like to be able to make a link to a page with a datatable which would pass a search parameter value in the url. The goal is to have the page with the datatable open pre-filtered with the search value parameter.

I've set up a jsfiddle to work in with some sample data.
http://jsfiddle.net/lbriquet/9CxYT/10/

The idea would be to add a parameter to the jsfiddle url so that the page would display with the search input value set to "firefox", for example, and the table filtered to show only the search matches.

Any help would be really appreciated!!

like image 718
lbriquet Avatar asked Jun 26 '12 22:06

lbriquet


3 Answers

This is an old question, but it still pops up high when searching for a solution. Here's what I did to make it work.

$(document).ready( function() {
  
  // First, get the search parameter. Here I use example.com#search=yourkeyword
    var searchHash = location.hash.substr(1),
        searchString = searchHash.substr(searchHash.indexOf('search='))
		                  .split('&')[0]
		                  .split('=')[1];
  
  
  $('#example').dataTable( {
    "oSearch": { "sSearch": searchString }
  } );
} )
like image 195
wouter Avatar answered Oct 21 '22 10:10

wouter


You could simply have a function that reads your URL var and then filter the table. I imagine that you pass q=Firefox as your search

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
 var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;

}

$(document).ready(function() {
    // Get the query from the url
    var query = getUrlVars()['q'];
    // create the table
    var oTable = $('#example').dataTable();
    // Filter it
    oTable.fnFilter( query, 2 );
});

Fiddle here http://fiddle.jshell.net/9CxYT/17/show/?q=Firefox

like image 45
Nicola Peluchetti Avatar answered Oct 21 '22 10:10

Nicola Peluchetti


Here is what I did to get it to work:

The first part from @Ibriquet gets the GET parameters from the url, I didn't change that. Quite possibly there is a nicer way to do this, but I didn't research that.

// Read a page's GET URL variables and return them as an associative array.
function getUrlVars()
{
 var vars = {};
    var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) {
        vars[key] = value;
    });
    return vars;

}

For the second part I included this within the $('#tablename').DataTable( { here, right after the column setup }

      initComplete: function() {
        this.api().search(getUrlVars()['search']).draw();        
      },

This puts anything after the ?search= and before any & in your url into the search field.

like image 1
Michael Paul Avatar answered Oct 21 '22 11:10

Michael Paul