Partial render not working on ajax call rails

421 views Asked by At

I am trying to reload a partial with a page (not the whole) page when I click on a button. When i click on button reset_me, it should reload the partial. Even though the partial is being called, the javascript inside js.haml is not executed.

routes

post :reset_filter, defaults: { format: 'js' }

controller action

def reset_filter
  respond_to do |format|
    format.js { render 'reset_filter.js.haml', layout: false }
  end
end

inside reset_filter.js.haml

$("#reset_me").html("#{j render partial: 'reset'}")
$('#reset_me").text('i have reset') // does not work as well

reset.html.haml

= button_tag 'Reset me', type: 'submit', disabled: false, id: 'reset_me'

show.html.haml

= render 'reset'

Javascript to trigger ajax call

reloadSidebar() {
  const requestInit = {
    method: 'POST',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
    },
    credentials: 'include',
    body: {}
  }

  fetch('full_controller_path', requestInit);
}

const resetAllElement = document.getElementById('reset_me');
.addEventListener('click', (e) => {
  reloadSidebar();
})

When I click the text should change. I traced it in console and it executes the .js.haml file, but javascript is not executed. Response from API also returns html with correct information ie. full html. Can someone help me find missing puzzle?

1

There are 1 answers

0
Lam Phan On

so your problem is not about render partial views but your js response is not executed, and you don't want to use ujs

i think you could use eval to execute js response

fetch (base on your code)

fetch('full_controller_path', {
  method: 'POST', 
  headers: {
    'Content-Type': 'application/json',
  },
  body: ...
})
.then(response => eval(response))

ajax

$('reset_me').bind('ajax:complete', function(event, xhr, status) {
 if (xhr.getResponseHeader('Content-Type').match("text/javascript")) {
   eval(xhr.responseText);
 }
  // ...
});

Note: there's warning Never use eval()!, and you also have another choice, just return json data instead of js and handle json response by js code on front end.