1

In my Rails app, I want to render a js.erb partial after a fetch call and for some reasons I do not understand it does not work. If you can help me, it would be great.

In a view, an event trigger this function that basically do a fetch request:

function updateState(id, state){
      const csrfToken = document.querySelector('meta[name="csrf-token"]').attributes
          .content.value;
      fetch(window.location.origin + "/update_state", {
          method: "POST",
          headers: {
            'Accept': "JS",
            "Content-Type": "application/json",
            "X-CSRF-Token": csrfToken
          },
          body: JSON.stringify({'id': id, 'state': state}),
          credentials: "same-origin"
        })
}

Then in my controller:

  def update_state
    @model = Model.find(params[:id])
    authorize @model
    @model.update(state: params[:state])

    respond_to do |format|
      format.html { redirect_to xxx }
      format.js
    end
  end

In my js.erb files:

console.log('hello');

However, in that case, I get an error from the server: ActionController::UnknownFormat at the line 'respond_to do |format| I have the feeling that the server do not understand the header of the fetch: 'Accept': "JS"

When I look at the logs of the server:

Started POST "/update_state" for 127.0.0.1 at 2019-04-04 11:22:49 +0200
Processing by ModelsController#update_state as JS

But I think that Rails does not recognize it. How do I do?

I tried also this in the controller:

  def update_state
    @model = Model.find(params[:id])
    authorize @model
    @model.update(state: params[:state])
    render 'update_state.js', layout: false
  end

Which does not fire errors. I received in the client side the js.erb. However, it is not executed (console.log does not execute).

Do you have any idea? Thank a lot for your help.

2
  • Comment out the header section and see what happens.
    – CAmador
    Apr 4, 2019 at 11:02
  • I can't remove the header. Otherwise, it raises an error: - Removal of Accept --> will redirect directly to the html (format.html) - Removal of the Content-type --> will not recognize the body of the fetch - Removal of the X-CSRF-Token --> will raise a ActionController::InvalidAuthenticityToken
    – Thomas
    Apr 5, 2019 at 7:57

3 Answers 3

1

I manage the other way around. I never succeded with js.erb.

So I use a fetch call with a response in text:

function updateState(id, state){
  const csrfToken = document.querySelector('meta[name="csrf-token"]').attributes
      .content.value;
  fetch(window.location.origin + "/update_state", {
      method: "POST",
      headers: {
        'Accept': "JS",
        "Content-Type": "application/json",
        "X-CSRF-Token": csrfToken
      },
      body: JSON.stringify({'id': id, 'state': state}),
      credentials: "same-origin"
    }).then(response => response.text())
      .then(data => {
       div.inserAdjacentHTML('XXX', data);
    });
}

Then in the controller/action:

  def update_state
    @model = Model.find(params[:id])
    authorize @model
    @model.update(state: params[:state])
    render 'update_state.js', layout: false, content_type: "text/plain"
  end

That way, it works. Hope it helps.

1

Edit : look at the edit for a fully working solution on triggering manually a .js.erb file.

Had the same issue and there are actually two problems here. Your are right, your headers are not. These headers to trigger the .js.erb worked for me and seems pretty right :

'dataType': 'json',
'contentType': 'application/json; charset=utf-8',
'X-Requested-With': 'XMLHttpRequest',
'X-CSRF-Token': - your CSRF method to get the token -

But secondly to trigger the js response, your respond_to block :

respond_to do |format|
  format.html { redirect_to xxx }
  format.js
end

Has to have the format.js first. As rails has a response for the HTML it will respond with HTML first and seems to not even look for the next format block.

respond_to do |format|
  format.js
  format.html { redirect_to xxx }
end

Hope it helps :-)

Edit 13/11/2018

Hey, long time no see ! The same issue happened to me again and my own previous reply wasn't solving the issue. Like you, the .js.erb file was rendered but nothing happened and the console.log was not displayed. So I created a link_to with remote: true that triggered my .js.erb file and compared the requests. Everything was the same except one thing : the type of the request. One was a fetch, the other was an xhr. It appears that the .js.erb files are triggered only by the xhr requests. So the solution is to build an old xhr request instead of a fetch, like this :

    const url = 'your_custom_path' // Build the url to fetch
    const csrf = document.querySelector('meta[name="csrf-token"]').getAttribute('content')

    let xhr = new XMLHttpRequest();

    // Will be a GET request here
    xhr.open('GET', url, false);
​    
    // Setting the headers
    xhr.setRequestHeader('Content-Type', 'application/json');
    xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
    xhr.setRequestHeader('X-CSRF-Token', csrf);
    xhr.setRequestHeader('dataType', 'script');
​
    // What to do with the response
    xhr.onload = function() {
      let responseObj = xhr.response
      eval(responseObj) // You need to eval() manually the response for it to be executed
    }
​
    // Sending the request
    xhr.send()

Hope it helps, even some months later! ;)

3
  • Thank you for your answer! However it does not work completly. Indeed, when changing the headers & switching the format lines, I do not get any errors. However, I come back to the other option of my question: I received in the client side the js.erb. However, it is not executed (console.log does not execute). Do you have any other idea? I really do not understand.
    – Thomas
    May 13, 2019 at 14:30
  • Hey ! Found to solution to your issue. Should be working now. Exactly 6 month day for day :)
    – Holino
    Nov 13, 2019 at 17:01
  • Understood! Thanks.
    – Thomas
    Nov 25, 2019 at 8:47
0

I ran into this issue in Rails 6 using fetch. My issue was solved by simply placing format.js above format.html. Thanks @holino. The following fetch works.

  fetch(event.currentTarget.dataset.destroyPath, {
    method: 'DELETE',
    dataType: 'script',
    credentials: 'include',
    headers: {
      'X-CSRF-Token': csrf
    },
  })

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.