2

I'm using datatables in my rails 3.1 application. Datatables is set up to work server side. I'm using ajax requests to get data from server and then display it in the table.

I use meta_search as a filter to get data from the database.

Here is the code in my view:

= simple_form_for @search, :url => offer_coupons_path(@offer), :html => {:method => :get} do |f|
= f.select :redeemed_equals,  [['All Coupons', '']] + [["Redeemed", true], ["Not Redeemed", false]]

Here is the method in the controller:

def offer_coupons_list
  search_params = params[:search] || {"meta_sort"=>"user_full_name.asc"}
  @search = Coupon.search(search_params)
  @coupons = @search.includes(:user).includes(:order => :gift).page(@page)
  render :partial => 'coupons/offer_coupons_list'
end

And here is javascript responsible for sending ajax request to the server:

$("#search_redeemed_equals").change(function(e){
    table = $("#grid").dataTable();
    var data = $("#search_redeemed_equals").parents("form:first").serialize();
    $.ajax({
        'url': 'coupons/offer_coupons_list',
        'data': data,
        'type': 'POST'
    });
    table.fnDraw();
    e.preventDefault();
});

The problem is that the script sends two ajax requests to the server. The first request is correct and returns filtered data. Another request is sent when fnDraw() is invoked and returns not filtered data. So the data in the table is not changed. Request is sent each time any of datatables functions is invoked. How can i solve the problem?

roman
  • 5,100
  • 14
  • 44
  • 77

1 Answers1

0

I think that the problem is that you are inizializing the table inside the event handler and so you call the server twice.

$("#search_redeemed_equals").change(function(e){
    table = $("#grid").dataTable();//one call to the server and you use a global variable!
    var data = $("#search_redeemed_equals").parents("form:first").serialize();
    $.ajax({
        'url': 'coupons/offer_coupons_list',
        'data': data,
        'type': 'POST'
    });
    table.fnDraw();//second call
    e.preventDefault();
});

i think you should take out the inizialization

var table = $("#grid").dataTable();

$("#search_redeemed_equals").change(function(e){
    table = $("#grid").dataTable();//one call to the server and you use a global variable!
    var data = $("#search_redeemed_equals").parents("form:first").serialize();
    $.ajax({
        'url': 'coupons/offer_coupons_list',
        'data': data,
        'type': 'POST'
    });
    table.fnDraw();//second call
    e.preventDefault();
});

if you already initialize the table in another part of your page, just assign the table to a javascript variable and call fnDraw on that

Nicola Peluchetti
  • 76,206
  • 31
  • 145
  • 192