Should I wait for ajax to complete to redirect a page?
Asked Answered
Y

3

6

I know how to wait for ajax to complete, but if I'm going to redirect a page after some ajax calls are fired off, should I wait for them to complete before the redirect? Does it matter?

Yawn answered 18/7, 2013 at 23:31 Comment(1)
I guess that depends if you need to do some errorhandling around the status code returned by the ajax call. If you redirect before it finishes how would you know it went through correctly?Boo
D
6

If you're confident that the ajax call will be successful, then once the ajax call has occurred, redirecting won't affect it as far as your server is concerned. But don't forget, the client could lose their connection or a number of errors could occur, so you should probably wait to make sure the calls were successful. Another thing to consider is whether or not your ajax calls will affect whatever page you're going to redirect to. In that case DEFINITELY wait before redirecting. You won't want your user to get redirected to a broken page because their connection was slow or your server had a hiccup.

Defective answered 18/7, 2013 at 23:34 Comment(3)
True true. An ajax call that counts page views for example can just be fired off an forgotten.Ephialtes
Is ajax a good way to count page views? Won't count users with JS switched off.Pier
Only about 2% of users have javascript disabled: #9479237. So really it depends on how accurate you want to be... I usually just ignore those people personally.Barlow
D
1

I recommend waiting and handling possible errors that might occur.

You gain safe connection, error spotting, better software, by doing the whole process synchronously, making the redirection coming in the end.

You might spend 0.1 second more of execution but who cares?

Deucalion answered 18/7, 2013 at 23:37 Comment(2)
Not true, it the process what I want to do from ajax is something what goes for 20secs. So cares.Exemplar
Been a while since I made this comment. What I should have been clear on, and I was basically implying the same thing as the accepted answer, is that if you can absolutely guarantee that the execution will be successful then sure, you can redirect, but there's a chance that the connection will simply get lost or an exception will come up that you want to be able to handle.Deucalion
R
1

I would argue that Ajax followed by a redirect is not a good use case for Ajax. Instead I would recommend doing a regular server request and then take care of all operations on the server before redirecting to your final destination.

This will make for a simpler pattern and a lot less network traffic. I recommend to use Ajax in cases where you want to avoid reloading the page. However in your scenario, you are planning on leaving the page as soon as your operations have completed, so why not avoid the back and forth that Ajax will give you.

Resendez answered 18/7, 2013 at 23:48 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.