jquery Development Tip #1

I ran into a problem today while working on a web application. The app itself is HTML5 and JS on the front and PHP and MySQL on the back. I noticed that each time the submit button was clicked, the click event handler was firing twice. I couldn’t figure out WHY this was happening, so I had to visit Stack Overflow.

The issue is one that I have not yet encountered, and I’ve been working with Java Script and jquery for a fairly long time. The event handler works by grabbing data from the form, passing it through to a URL via ajax request, and then reloads the original entry form page—which happens to contain the Java Script. What I believe was happening is that, because I have the script on the entry form page and I’m reloading that page upon successful database entry, the “event” is still in progress. As a result, I’m redefining the event handler for the ongoing event, thus stacking them together. This results in two events firing. Obviously, this is no good and my DB was starting to fill up with massive duplicate entries.

I finally ended up finding out about this nifty jquery event handler attachment, called ‘one’. This basically ensures that the event only fires a single time. I love easy fixes, but even more, learning something new in the process. Here’s an example use:

$("#buttonId").one.("click", function() { 
    // do stuff
});
Advertisements