Spot the error - it may not be what you think

I just helped a coworker diagnose this issue and it can be incredibly subtle if you aren’t paying attention. Consider the following simple form:

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() { $("#myButton").click(function() { $.post("test.cfc?method=whatever&returnformat=json", {}, function(res) { console.log('back from cfc'); },"json"); }); }); </script> </head> <body> <form method="post"> <input type="button" id="myButton" value="Click me like you mean it."> </form> </body> </html>

I've got a button that - when clicked - will fire off an event jQuery is listening to. This event handler fires off a post to a CFC with the result then logged to the console. Works perfectly. Now let's tweak it just a tiny bit...

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() { $("#myButton").click(function() { $.post("test.cfc?method=whatever&returnformat=json", {}, function(res) { console.log('back from cfc'); },"json"); }); }); </script> </head> <body> <form method="post"> <input type="image" src="meatwork.jpg" id="myButton" value="Click me like you mean it." > </form> </body> </html>

Can you guess what happened here? Try to before scrolling down...






















So - when clicked - if you had your network tools open in Chrome or Firefox, you would see a quick glimpse of a request and then it would go away. Why? The image input type is actually like a submit button. Unlike type=button that does - well - nothing - the image type actually works much like a submit button. What happened was that the entire form posted. Easy to miss especially if you are testing locally. A quick fix is to just prevent the default behavior:

$("#myButton").click(function(e) { e.preventDefault(); $.post("test.cfc?method=whatever&returnformat=json", {}, function(res) { console.log('back from cfc'); },"json"); });

Anyone else ever get bitten by this?

Raymond Camden's Picture

About Raymond Camden

Raymond is a developer advocate looking for his next gig. He focuses on JavaScript, serverless and enterprise cat demos. If you like this article, please consider visiting my Amazon Wishlist or donating via PayPal to show your support.

Lafayette, LA https://www.raymondcamden.com

Comments