Michael Waxman
Michael Waxman

Reputation: 1825

Prevent Rails app from responding to unintended AJAX request from jQuery

I've built out a fairly complex Rails (2.3.8) app with a lot of jQuery ajax requests. There is an occasional bug, which I have difficultly replicating, where a jQuery $.ajax({..}) request will request a page it shouldn't (like the dash page, which is never called with an ajax request)...

What ensures is absolutely madness. Incredibly strange and terrible errors happen.

For at least a stopgap solution (the app is in production), how can I set up a before filter than will detect any unsolicited xhr/ajax request (or ANY such request on the given controller actions) and kill it before it hits the controller?

Upvotes: 0

Views: 257

Answers (1)

Leventix
Leventix

Reputation: 3859

In any controller:

before_filter :stop_ajax, :only => [:dashboard]

application_controller.rb:

def stop_ajax
  if request.xhr?
    render :file => "#{Rails.root}/public/404.html", :status => 404
  end
end

Upvotes: 2

Related Questions