Home > other >  Passing Json response to view in Rails Ajax Datatable
Passing Json response to view in Rails Ajax Datatable

Time:09-22

I have an index method that respond with Json call to Datatable such as:

respond_to do |format|
  format.html
  format.json { render json: PeopleDatatable.new(params, user: current_user, view_context: view_context) }
end

I would like to be able to pass an array of all the IDs in the response to a dom in my view such as <div id: "people">1,2,3,4</div>

As per the gem description, the People records are generated in the

app/datatables/people_datatable.rb

using:

def get_raw_records
  User.all
end

I tried adding the following in the view's script:

$(document).ready(function () {
    $.ajax({
        type: "GET",
        url: "<%= peoples_path(format: :json) %>",
        dataType: "json",
        success: function(data) {
            alert(data.name)
            $('#bouba').html(data);
        }
    });
});

but the result is an undefined object class.

What would be the easiest way to do so please?

I am using the following gem for my datatable Rails ajax Datatable

CodePudding user response:

Open /people.json and see what you get as a response, it looks something like this:

{
  "recordsTotal": 2,
  "recordsFiltered": 2,
  "data": [
    {
      "id": "1",
      "name": ""
    },
    {
      "id": "2",
      "name": ""
    },
  ]
}

Now that you know what the structure looks like, send ajax request to that url:

<div id="people-ids"></div>

<script type="text/javascript">
  $(document).ready(function () {
    $.ajax({
      type: "GET",
      // send request to the correct url: "/people.json"
      url: "<%= people_path(format: :json) %>",
      dataType: "json",
      success: function({data}) {
        //              ^
        // extract "data" attribute from the response

        console.log(data) // you can see what you get in the console
        
        // extract ids
        const user_ids = data.map(user => user.id)

        // do what you like with the ids
        $("#people-ids").html(user_ids.join());
      }
    });
  });
</script>
  • Related