Reputation: 2908
how do I refresh a rails path with an error message using ajax. I'm waiting for a callback from a payment API and if I get an error I want to reload the page and show the error. Problem is I'm using ajax. How can I pull this off ?
Upvotes: 1
Views: 1204
Reputation:
Refreshing the page to display a simple feedback error is completely unnecessary and long-winded. A much cleaner, and more direct method, is to use js to update the dom within the callback.
A very very simple demonstration:
$(".errors").append('<li>My error</li>');
In the name of simplicity, do that (or something similar within javascript), don't redirect just to display an error.
Upvotes: 1
Reputation: 18037
In the action that responds to the AJAX request you can do
flash[:alert] = "My error"
And then have the action render the redirect as such:
render js: "window.location.href = '#{my_named_route_path}'"
Or, you may want to write a method to abstract this, such as:
app/controllers/application_controller.rb
def redirect_to_via_xhr_if_applicable(url, options = {})
flash[:info] = options[:info] if options.key?(:info)
flash[:alert] = options[:alert] if options.key?(:alert)
flash[:notice] = options[:notice] if options.key?(:notice)
if request.xhr?
render js: "window.location.href = '#{url}'"
else
redirect_to(url)
end
end
Then you can just make this call from your AJAX (or non-AJAX) action:
redirect_to_via_xhr_if_applicable(my_named_route_path, alert: 'My error!')
Upvotes: 1
Reputation: 4596
If error is persisted on database, you can use window.location on callback function in order to relaod the page with errors.
Upvotes: 1