Rails: Respond with js to Ajax request

3.1k views Asked by At

I encountered some weird behaviour when using an ajax request to get a response from a rails controller action.

$.ajax({
    type: 'GET',
    url: '/notifications',
    success: function(result) {
        eval(result);
    }
});
def index
    respond_to do |format|
        format.html { redirect_to root_url, alert: 'Page not accessible' }
        format.js
    end
end

So this respond_to block works fine when using requests with rails' remote: true option, but with the ajax call it just redirects the request to root_url.

When specifying json as dataType of the Ajax request. The so returns the JavaScript just fine, but because it is not valid json, eval() does not run it.

Is there a way too either start a rails remote request from within JavaScript or specify a data type with which the returned JavaScript is executable?


Even specifying dataType: 'text/javascript', in the ajax call does not do the trick.

1

There are 1 answers

4
Pavan On

So this respond_to block works fine when using requests with rails' remote: true option, but with the ajax call it just redirects the request to root_url

So the request format that is coming to the controller is HTML not JS. Using dataType: 'script' generates the request as JS and should fix your problem.

$.ajax({
  type: 'GET',
  dataType: 'script',
  url: '/notifications'
});