简体   繁体   中英

Rails 5: How to get controller data in the AJAX response?

I have referred so many articles on the topic, after which I have ended up more confused than understanding anything clearly. It mainly because of the many ways the same thing is done in rails.

Old school method of making ajax calls: 1. Javascript watches for some event. 2. When that event occurs (for example: button click) , you catch that in javascript, make an ajax call, handle the success or error response within that ajax call.

Trying to do this with rails 5, the rails way: 1. Having problem in getting the data from controller to javascript.

controller:

class SomeController < ApplicationController
  def show
  end

  def foo
    @result = 'Hello World'
    respond_to do |format|
      format.js {@result}
    end
  end
end

In my view I have a form which has remote: true, and is responsible for submitting the AJAX request to the foo action in the controller. Something like:

=form_tag url_for(action: 'foo'), remote: true, id: 'element-form' do
  =some input ....
  =some input ...

Javascript: foo.js.erb in /views/some/foo.js.erb

$('#element-form').on ('ajax:complete', doSomething)

function doSomething(event, data) {
  console.log(data) // prints undefined
}

$('#element-form').on ('ajax:error', doSomethingElse)

function doSomethingElse(event, data) {
  console.log(data) // prints undefined
}
  1. What is it that I am doing wrong, because of which I can't seem to access the data from controller in the ajax onsuccess function?
  2. I feel very icky about using the *.js.erb file. I kind of feel like I am mixing up everything (views and javascript).
  3. If I don't want to use *.js.erb for my javascript, but I still want to do AJAX calls the rails way (using the remote: true, respond_to...), is there a way I can pass my controllers data to my javascript files where I will be handling the AJAX response.
  4. How can I define the success and error handlers for ajax response separately? Is there some rails convention that I am missing, which provides this automagically?

When I inspect the ajax call in the browser, I can see that I am getting a valid response that includes the entire javascript that is defined in the foo.js.erb file.

My biggest problem is not any particular piece of code, but understanding how all of the pieces fit together. To summarize, I just can't seem to get the data-flow or the request response cycle that take place when making an ajax request in a rails 5 environment. Links to any references on this topic is highly appreciated.

foo.js.erb is an ERB view, like any other. So you reference your controller data as usual.

 console.log("<%= @result %>");

(you don't need to setup that ajax:complete in the .js.erb, btw)

So I finally was able to get the whole ajax request response cycle to work. Here's how I set up the whole thing.

The controller logic remains the same. In-order to get finer control over the ajax request, I included the logic in the some_controller.js file. As Sergio pointed out in one of his comments, in his answer, I think its too late to add any callback methods in the *.js.erb file.

So the javascript code looks like below:

$(document).ready(function() {
  $('#some_element').on('some_event', function doSomething() {
    makeAjaxCall();
  });

  function makeAjaxCall() {
    Rails.ajax({
        type: "POST",
        data: {mock_data: mock_data},
        url: 'post_url',
        success: function(response){...},
        error: function(error){...}
      });
  }
});

Now the important part is what happens when your post method in rails controller (action) completes. I believe rails is looking for some view to render. In this case it looks for a js view which should have the same name as the action method (action_method.js.erb)

So any controller data that you want to send to the ajax callback blocks, can be simply put in this js view. So in my case the Javascript: foo.js.erb in /views/some/foo.js.erb changed to:

<%=@result %>

After all this, the control comes back to the client side javascript, which in our case is the ajax success callback method and whatever you put in the *.js.erb file becomes available to you in the response.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM