I am having trouble with my javascript. It seems to be acting oddly. This is what\'s going on. I have a form, after the user submits it, it calls a function(onsubmit event)
The problem is that XMLHTTPRequest is asynchronous - it sends the request in the background and doesn't wait for it to finish.
The alert
statement causes the code to wait until the user clicks OK, during which the request finishes.
You need to use the onreadystatechange
event, like this:
xmlhttp.onreadystatechange = function() {
if(xmlhttp.readyState==4) {
// Do things
}
};
The method you assign to this property will be called after the response is received. (and at other times, which is why you need to check that readyState
is 4)
That is because your AJAX call is asynchronous. The code following xmlhttp.send()
is executed immediately. It doesn't wait for your ajax call to end (unless you put the alert).
Move all the code to be executed after the ajax call to the callback method to ensure it is run after the call is finished.
[Edit]: Aside from the problem, I think using AJAX just to validate the form and then allowing the user to submit the usual way seems a bit odd to me.
Can you divide the validation into 2 parts? One that can be done purely on the client side and the other which involves the server-side validation. You can do the second part completely on server-side upon submit and return the errors back to client.
Another option is to avoid the traditional submit altogether. Since you are doing the ajax call anyway, why don't you do the save/edit/whatever in the ajax call itself removing the need for a submit? Keep in mind though, you will still need to support the regular submit if the user has javascript disabled.
<?php
usleep(200000)// 2 seconds
after the javascript (which btw, entailed deferring jQuery 1.9.1 to the head