EastsideDev
EastsideDev

Reputation: 6659

Passing variable to controller through Ajax call

Rail 5.2
datatables

In my views/books/index.html.slim, I am loading a partial, from another MVC, as follows:

 = render  partial: 'authors/index', :locals => {:author => @book.author}

In my views/authors/_index.html, I have the following:

.....    
table.table-striped.table-bordered.table-hover.nowrap#AuthorsIndex.display
.....

javascript:
  $('#AuthorsIndex').DataTable({
    ajax: '/authors',
    columns: [
      {title: 'Publish Date', data: 'created_at'},
      {title: 'Publisher', data: 'publisher'},
      {title: 'Title', data: 'title'},
    ]
  });

And, in my controllers/authors_controllers.rb, I have the following:

def index
  @authors = Author.where(author: "John Doe")
  render json: { data: @authors }
end

When I run it, the authors table displays properly. The problem, is that the author name is hard coded in the controller action. My _index partial, is receiving the author name, but how do I get it to the authors controller, as part of the Ajax call I am making? New to Ajax/Javascript.

Upvotes: 0

Views: 535

Answers (2)

3limin4t0r
3limin4t0r

Reputation: 21160

I don't have the necessary tools installed to test this, but the jQuery DataTable documentations says that you can provided custom data through the ajax.data option.

The ajax.data option provides the ability to add additional data to the request, or to modify the data object being submitted if required.

...

As an object, the ajax.data option is used to extend the data object that DataTables constructs internally to submit to the server. This provides an easy method of adding additional, static, parameters to the data to be sent to the server. For dynamically calculated values, use ajax.data as a function (see below).

The documentation also provides example scenarios, and goes further into detail about what can be provided.

$('#AuthorsIndex').DataTable({
  ajax: {
    url: '/authors',
    data: {author: '<%= j author %>'}
  },
  columns: [
    {title: 'Publish Date', data: 'created_at'},
    {title: 'Publisher',    data: 'publisher'},
    {title: 'Title',        data: 'title'}
  ]
});

Then in the controller:

def index
  @authors = Author.where(author: params[:author])
  render json: { data: @authors }
end

Upvotes: 1

sameera207
sameera207

Reputation: 16629

How about

#_index.html
javascript:
  $('#AuthorsIndex').DataTable({
    ajax: '/authors?author=<%= author %>',
    columns: [
      {title: 'Publish Date', data: 'created_at'},
      {title: 'Publisher', data: 'publisher'},
      {title: 'Title', data: 'title'},
    ]
  });

#authors_controllers.rb
def index
  @authors = Author.where(author: params[:author])
  render json: { data: @authors }
end

Upvotes: 1

Related Questions