TLDR: Can the onreadystatechange event be emulated somehow else for synchronous requests without freezing the browser, as it does not get fired in Firefox?
~~~~~
I have created a web form that needs verification and to get some elements from the server before actually being submitted.
What I do now, is that 'onsubmit' I fire an ajax request to my server, send the form details, parse them server side, and return a unique verification number and a md5 hash to the form.
The way it is meant to work is that the form should receive the reply and then proceed to submit the form. I must note that the actual form submission is a normal POST submission without ajax – the form is posted to a server outside my control.
I suppose I need to do a synchronous ajax request – not asynchronous as it is often used for. The point is that the form should never be submitted before getting the reply, simply because it will fail, as the reply contains important fields that the server on the other side will look for.
I tested Chrome and everything seems to work fine with synchronous requests. I do the request, and onreadystatechange I fire the handler to parse the reply.
But Firefox does not fire the onreadystatechange event in synchronous requests. This behavior is there from version 1.5 or something.
What most people do, as I’ve seen, is to run the handler anyway at some point – because the response is received and is in the DOM (responseText), just the onreadystatechange event doesnt get fired.
But this does not work for me: Depending on where on the code I run it, the response may not be available yet, so parsing it will fail.
I’ve tried two solutions, both of them bad:
- Use a synchronous request, and put the handler on a while loop, waiting for the reply.
- Use a asynchronous request, and have a while(myvariable); to wait until the reply gets there (myvariable is the reply I get from the server, after handling the responseText.
Both of these of course cause Firefox to freeze for quite some time, as Javascript waits in a while loop. In the end it works fine, if the anti-freeze protections of Firefox don’t kick in and say that a script on this page is not responding.
What would you suggest? Can I do a while loop without freezing the browsers? Maybe a polling thingie that doesnt poll every millisecond as the while loop does, but every 1 second lets say, so the script doesn’t freeze?
If your request is synchronous, then once the send() call returns the reply is completely available. That’s the whole point of synchronous requests. Why do you need to do any sort of looping at all in that case?