My Ajax call returns js.erb file as the response in the browser. How do I make it return json contents, but also execute the js.erb file?

rails render js
format.js rails
rails 5 ajax render partial
rails ajax get data from controller
rails ajax render partial
rails-ujs ajax
rails ajax example
rails remote: true not working

I'm new to Ruby on Rails and trying out an application. My application does Ajax calls correctly, but the response is shown as a js.erb file in the browser. How do I show a json response while executing the js.erb file? Is it possible or is there a better way?

Thank you.

My Controller File

def new
  @department = Department.new
  # respond_to do |format|
  #   format.html
  #   format.json {render json: @department}
  # end
end

def create
  @departments = Department.all
  @department = Department.create(department_params)
  respond_to do |format|
    format.html
    format.js {render json: @department}
  end
end

Controller

My Form Partial

<div class="modal-dialog">
  <div class="modal-content">
  <%= form_for @department, remote: true, data: {type: :json} do |f| %>
  <div class="modal-body">
    <h2> Department: </h2>
    <ul class="errors"></ul>

    <div class="form-group">
      <%= f.label :title, class:"control-label" %>
      <%= f.text_field :title, class: "form-control" %>
    </div>
    <div class="form-group">
      <%= f.label :body, class: "control-label" %>
      <%= f.text_field :body, class: "form-control" %>
    </div>
  </div>
  <div class="modal-footer">
    <%= f.submit class: "btn btn-primary .departmentCreate" %>
    <%= link_to "Cancel", "#", class: "btn", data: {dismiss: "modal"} %>
  </div>
<% end %>
</div>
</div>

Form.html.erb

My Json Response if I keep format.js {render json: @department} Json Response

My Response if I remove render json from controller: JS response

My new.js.erb File

$("#department-modal").html("<%= escape_javascript(render 'departments/new') %>")
$("#department-modal").modal("show")

My _new.html.erb partial :

<%= render "form" %>

My create.js.erb file:

<%= render 'save' %>

My _save.js.erb partial:

$("ul.errors").html("")
<% if @department.errors.any? %>
  <% @department.errors.full_messages.each do |message| %>
    $("ul.errors").append($("<li />").html("<%= message.html_safe %>"))
<% end %>
<% else %>
  $(".department-index").html("<%= escape_javascript(render 'departments/index') %>")
  $("#department-modal").modal("hide")

While rendering the json response in browser, the js.erb file doesn't execute. How can I show json response in browser while js.erb file executes? Thank you :)

How can I show json response in browser while js.erb file executes? Thank you :)

If I understood correctly what you are asking, the answer is you can't. Your response's Content-Type will be either an application/json or an application/javascript.

The browser will use this header to handle the response.

How to Use AJAX With Ruby on Rails, Let's understand why AJAX exists, so you can get a better idea of how to use it in the browser using Javascript, and the response, which you handle from your Ruby app. It involves returning only the data as JSON, then generating the HTML Put this code in a file with an extension of .js.erb , with the name of the current� I'm still working on learning Rails, and I have a page with team information that will get updated based on a team's icon click, which fires an ajax call to the controller to populate some tabs. I've read some good info about how to use format.js in the controller to render a partial from a js.coffee or js.erb file.

The reason your JavaScript is not executing is because you have a block present in your controller that handles the response. So the code will never reach your JavaScript file.

Change the line:

format.js { render json: @department }

to:

format.js

This will tell Rails that you accept JavaScript request, and since no block is specified the template in "app/views/departments/create.js.erb" is used.

If you don't want to render the default template you can specify it in the block like so:

format.js { render: :new } # renders app/views/departments/new.js.erb

or:

format.js { render: 'some/path' } # renders app/views/some/path.js.erb

Working with JavaScript in Rails — Ruby on Rails Guides, How to include your Cross-Site Request Forgery token in request headers. In order to understand Ajax, you must first understand what a web browser does normally. It parses the response, then fetches all associated assets, like JavaScript files JavaScript can also make requests to the server, and parse the response. Ajax is a technology that allows developers to make asynchronous HTTP requests without the need for a full page refresh. To make the process less cumbersome than it would be in pure JavaScript

Instead of nested rendering of js.erb direct render template from controller with full path. assuming full path of _save.js.erb is departments/save Also @departments should be calculated after create new department so that newly created record will be added with @departments

def create
  @department = Department.create(department_params)
  @departments = Department.all
  render template: 'departments/save'
end

Its always a good practice to pass local variables with partial:_

$("ul.errors").html("")
<% if @department.errors.any? %>
  <% @department.errors.full_messages.each do |message| %>
    $("ul.errors").append($("<li />").html("<%= message.html_safe %>"))
<% end %>
<% else %>
  $(".department-index").html("<%= j render 'departments/index', departments: @departments) %>")
  $("#department-modal").modal("hide")

render html in js.erb Code Example, Get code examples like "render html in js.erb" instantly right from your google Your browser does not currently recognize any of the video formats available. Angular Quick Tip: Binding Specific Keys to the Keyup and Keydown Events comparing two array of objects in javascript returning differences� They all also use the same ajax call, so it probably isn't that, and the call is just a simple default ajax call to the current page (e.g.) $.ajax({ }); And triggering the articles#drafts action looks to be good in my rails server as it issues a correct GET response.

You cannot render both as such, but you can render the partial on the server side, and store the result in the JSON. On the client side, you can process JSON, and extract and use the rendered HTML snippet in JS code.

Syntax in Jbuilder for rendering a partial :

json.some_key json.partial! 'my_partial.js.erb'

So the stack is something like..

Controller

# Render the JSON partial in views

respond_to do |format|
    format.json {}
end

View - controller action will call default json builder for action e.g views/departments/new.json.jbuilder

In here render any original JSON you wanted, like @department, but also render the required JS partial and store it in the JSON

json.department @department


json.department_form json.partial! 'new.js.erb'

Then in the client code that receives the JSON, for example as data, the partial will be present under key department_form, and you can assign the rendered form, to an html placeholder element in your original view

     //... ajax call to your controller#action
     dataType: "json",
     success: function(data) {
                $("#department_form_placeholder").html(data['department_form'])

How to structure JavaScript code when using AJAX in , Skip to content AJAX is a great solution that allows you to send and retrieve data from in Rails to use the data from server by executing JavaScript code: AJAX If we want to receive a JSON response, we can set the dataType to json . The template supports ERB which allows you to insert Ruby code. I am trying to allow the user to create comments on a specific post, using AJAX in Rails. I get the form to show, but on create it does not work.

render (ActionController::Base), Renders the content that will be returned to the browser as the response body. Rendering will automatically insert the etag header on 200 OK responses. and with a 404 status code render :file => "/path/to/some/template.erb", :layout => true, If your controller action does not explicitly call render, Rails will, by default,� Add remote: true to your form Prepare your controller to respond with JavaScript: # CommentsController def create @comment = @topic.comments.create!(comment_params) respond_to do |format| format.html { redirect_to @comment } # no js fallback format.js # renders comments/create.js.erb end end Create the create.js.erb

Ruby on Rails - AJAX, Ruby on Rails - AJAX - Ajax stands for Asynchronous JavaScript and XML. data for a web page without having to refresh the contents of the entire page. can have the server return any kind of data in response to an Ajax request, Create a file, destroy.js.erb, put it next to your other .erb files (under app/views/ ponies). Get code examples like "how to make a ajax call in javascript" instantly right from your google search results with the Grepper Chrome Extension.

Please make it clear whether Rails.ajax is for internal use only , Any javascript in the template do_something.js.erb will execute. This may not apply to your problem, but this is the only use we have found for� To do this we call $(this) to get the current element, i.e. the checkbox that’s been checked, then call parent on that to get the parent form. Calling submit() on this will submit the form. We also want to remove the button on each form and we can do this getting the input elements with a type of submit and calling remove on them.

Comments
  • Could you add your code to the question as text instead of image?
  • Hey, I've added the code snippets.
  • It's unclear what you want to respond with. Can you rephrase your question?
  • @JagdeepSingh I've updated the question.
  • What does your js.erb template contain?
  • Yes, I've tried that. Now json response is not shown in the browser. It just shows the whole create.js.erb file in the browser response. What I actually want is to show the json, but also execute the js.erb file.
  • One request can only have one response. If you want the JS file to be executed this is the way to go. If you also want to do something with the JSON you'll have to do that inside your JS file. eg. $('#some-element').html('<%= j render(json: @department) %>'). (j is an alias for escape_javascript.)