5

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.

heroxav
  • 1,387
  • 1
  • 22
  • 65

1 Answers1

5

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'
});
Pavan
  • 33,316
  • 7
  • 50
  • 76