Jeff Locke
Jeff Locke

Reputation: 627

How to render .js.erb template and return JSON data

I have some javascript that calls a URL mysite.com/articles.js which sends a request to the articles controller's index action. I need to return data to the javascript function in JSON format but before that, I want to update some partials on the page by rendering index.js.erb

I'm calling the URL via jquery

var url = '/articles.js

$.get(url, function(newItemData) {
  someOtherFunction(newItemData)
}

Is calling the URL w/ a .js ending not the same as sending an AJAX request (remote => true) ?? I have some other buttons and links that send ajax requests via remote => true and the .js.erb template is rendered automatically with that request. Is there a way to call the URL as an ajax request?

Any help would be much appreciated.

Thanks!

Upvotes: 0

Views: 1498

Answers (1)

Henrique Zambon
Henrique Zambon

Reputation: 1301

Correct me if I'm wrong, but it looks like you're trying to render two views from your controller: the index.js.erb file and a JSON response. That is not possible, as Rails only supports one render, redirect_to or head call.

That means you'll need to change your JavaScript code to send two requests: one to update the view (render index.js.erb) and another to return your JSON object.

Submitting a request to a .js ending URL is not the same as submitting an AJAX request. For that you'll need to set remote: true, as you mentioned, or build an AJAX request in you JavaScript code ($.ajax(), if you're using jQuery).

You may also consider taking a look at Layouts and Rendering in Rails.

Hope that helps!

Upvotes: 1

Related Questions