0

Currently I'm working on a project which performs some client side validation (using Javascript) on a form when submitted and then based on an Ajax request, either makes a window.location.href redirect or submits the form to be handled by the controller.

My question, what is the best way to handle this situation? Should the form be directly submitted to the controller where the request will be processed or is the current method a better approach?

I feel the redirection based on the Ajax call is completely unnecessary since the controller can do this anyway.

2
  • I don't understand quite well the situation, when does the ajax request make a redirection? I guess when validations fail, but can you confirm it? Commented Aug 26, 2014 at 11:06
  • Yes that is correct. It can be confirmed in the success event handler, which is where it's redirected. Commented Aug 26, 2014 at 11:34

1 Answer 1

1

Your gut feeling is right. window.location.href is also not a redirect in a HTTP sense (which would be a HTTP status code 302 for example), but a completely new request.

There's a couple of benefits as a side effect:

  • easily testable with unit tests
  • you can use the controller logic from different locations (also as an API)
  • DRY: no code duplication in controller (where you need the redirect anyway) and the javascript
Sign up to request clarification or add additional context in comments.

4 Comments

I figured it wasn't an actual redirect since the browser's history also gets messed up if the application's javascript is not completely loaded. If I try to return to the previous page after the redirect, it skips a page. But that's a different question all together.
Thanks for the answer though. I guess I'll just have to refactor a bit of code to handle the redirection through the controller directly. I'll accept your answer by the end of the day if no one else answers :)
Thanks a bunch. If you have a follow up question, you can add it here.
And good luck with the refactoring. Write a couple specs to guard against regression(;

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.