Jadoo
Jadoo

Reputation: 21

How to pass array from js to controller

I have an array in my javascript file app/assets/javascript/pages/books_page.js :

var booksPage = Backbone.Model.extend({
  defaults: {
    authors: []
  }
  ...

How can I pass that to my controller as a param. The path of my controller is app/controllers/books_controller.rb ?

I think I might need an ajax request and tried the following but it is not working:

$.ajax({
        type: "post",
        url: "/books_controller",
        data: { list_authors: this.get('authors') },
      });

Specifically, I am not sure what the url needs to be. Your help here will be greatly appreciated. Thanks.

Upvotes: 0

Views: 193

Answers (3)

mu is too short
mu is too short

Reputation: 434755

Backbone (and jQuery) should do all the heavy lifting for you. Set the urlRoot in the model:

var booksPage = Backbone.Model.extend({
  urlRoot: '/books',
  ...
});

and then call save on the instance to send the data to the server:

// Get or create `books` as a `booksPage` instance as usual...
// Then make some changes to `books` using `books.set(...)`...
books.save();

Upvotes: 1

Tom
Tom

Reputation: 1320

type: 'POST', 
url: `/books/${this.id}`, // or '/books/' + this.id,
data: {
  _method: 'put'
}

This will route you to the BooksController#update. You also need to merge the _method entry into your data object.

"NOTE: Because submitting forms with HTTP methods other than GET and POST isn't widely supported across browsers, all other HTTP methods are actually sent over POST with the intended method indicated in the _method parameter. Rails automatically detects and compensates for this." - Working with JavaScript in Rails

Upvotes: 0

7urkm3n
7urkm3n

Reputation: 6321

You can use JSON.stringify, and parse it from Controller JSON.parse(params).

$.ajax({
      type: "post",
      url: "/books_controller",
      data: { list_authors: JSON.stringify(this.get('authors')) }
});

Upvotes: 0

Related Questions