Javascript and AJAX, only works when using alert()

The alert() helps because that delays the processing of the remaining javascript in that function (everything from the alert() down to the bottom), leaving enough time for the AJAX request to complete. The first letter in AJAX stands for “asynchronous” which means that (by default) the response will come in at “some point in the future” but not immediately.

One fix (which you should not implement) is to make the processing synchronous (by changing the third argument of open() to be false) which will stop further processing of your script (and the entire webpage) until the request returns. This is bad because it will effectively freeze the web browser until the request completes.

The proper fix is to restructure your code so that any processing that depends on the result of the AJAX request goes in to the onreadystatechange function, and can’t be in the main function that initiates the AJAX request.

The way this is usually handled is to modify your DOM (before the AJAX request is sent) to make the form readonly and display some sort of “processing” message, then in the AJAX response handler, if everything is okay (the server responded properly and validation was successful) call submit() on the form, otherwise make the form wriable again and display any validation errors.

Leave a Comment