Javascript and AJAX, only works when using alert()

前端 未结 9 1174
借酒劲吻你
借酒劲吻你 2020-12-01 15:01

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)

9条回答
  •  执念已碎
    2020-12-01 15:55

    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.

提交回复
热议问题