Max Kirsch
Max Kirsch

Reputation: 461

Rails parse JSON response for jQuery Datatables

I have a small problem with the ajax function of jQuery DataTables and with the JSON response, I get in my Rails 6 application. I'm successfully accessing the route and getting back a JSON response.

What I want to achieve: I count the number of records with specific attributes for every day, so I get back an integer value. My problem is: How can I pass this value to jQuery DataTables to appear in the columns?

My controller action:

 def showDailyOrders
    render json: 
    { count1: OrderCard.where(day: Date.today).where(dish_type: 0).count }
  end 

My jQuery code to initialize the DataTable and the AJAX request:

$("#todaysOrdersTable").DataTable({
            ajax: '/showDailyOrders',
            dataSrc: '',
            columns: [
                { title: 'Vollkost', data: 'count1' }
            ]
        });

The JSON response I get looks like this:

"{\"count1\":1}"

How do I pass the value (1 in this case) to the jQuery function? It's just telling me "Loading", but nothing happens. If I use another query like OrderCard.all as response and use the key (for example "id") as data in the function, it's displaying the value.

Thanks for any help!

Upvotes: 0

Views: 947

Answers (1)

3limin4t0r
3limin4t0r

Reputation: 21120

The dataSrc option does not exist and thus will be negated. Instead use the ajax.dataSrc option:

$("#todaysOrdersTable").DataTable({
  ajax: {
    url: '/showDailyOrders',
    dataSrc: ''
  },
  columns: [
    { title: 'Vollkost', data: 'count1' }
  ]
});

After fixing the dataSrc option you still have the issue that the returned value is a single value instead of an array. When you return OrderCard.all you return a array of values, which is why it works.

This means we have to convert the single returned object {"count1":1} into an array that holds the object [{"count1":1}]. This can either be done on the client- or server-side. On the client-side it should look something like this:

$("#todaysOrdersTable").DataTable({
  ajax: {
    url: '/showDailyOrders',
    dataSrc: obj => [obj], // transform into an array
  },
  columns: [
    { title: 'Vollkost', data: 'count1' }
  ]
});

Or if you rather change the server-side it should look something like this:

order_cards = OrderCard.where(day: Date.today).where(dish_type: 0)
# note that the object is now wrapped inside an array
render json: [{ count1: order_cards.count }]

Upvotes: 1

Related Questions