views:

171

answers:

1

Hi, I'm working on a security project in javascript (something I honestly have not used), and I'm having some trouble with EventListeners.

My code looks something like this:

function prevclick(evt) {
evt.preventDefault();
document.loginform.submitbtn.removeEventListener('click',prevclick,false);
var req = new XMLHttpRequest();
req.open("GET","testlog.php?submission=complete",false);
req.send();
document.loginform.submitbtn.click(); //tried this and loginform.submit()
}

document.loginform.submitbtn.addEventListener('click',prevclick,false);

But the problem is, the submit button doesn't submit the form on the first click (it does, however, send the http request on the first click), and on the second click of the submit button, it works as normal.

I think there is a problem with the synchronization, but I do need to have the request processed before forwarding the user to the next page.

Any ideas on this would be great. Thanks in advance.

A: 

remove the evt.preventDefault() line. And delete the last line of the function.

Jared Forsyth
Thanks that worked. Question though, could you perhaps explain why to me? Does the submit button wait for the event handler to return before executing the click? I thought that maybe it ran in another thread, which is why I tried prevent default.Also, why did preventDefault() cause the misbehavior? My understanding was that it prevented the single click event from reaching the intended results, but since I unhooked the same function from the button immediately after, the click() function would submit the form with default behavior.All this is pretty new to me, so thanks for the advice
Xzhsh
One thing that is important to remember about javascript in the browser is that it is *always* single threaded. Firing the click function from within the click handler probably failed because otherwise it would infinitely loop.
Jared Forsyth
Ahhh thanks! Got it.
Xzhsh