Yesterday I blogged about using ColdFusion's built in Ajax tools to add server-side database checking to a form. This worked, but I wanted to repeat the process using jQuery on the front end. What's nice is that while the front end may change, the ColdFusion Component I wrote on the back end doesn't have to change at all. Let's look at the new version - and as always - keep in mind that this could be rewritten many different ways.

<html> <head> <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script> <script> $(document).ready(function() { $("#artist").keyup(function(e) { var value = $.trim($("#artist").val()); if (value != '') { $.post("test.cfc?method=checkArtist&returnFormat=json", {n:value}, function(res,code) { if (res == true) { $("#warning").html("This artist exists."); $("#submitBtn").attr("disabled","disabled"); } else { $("#warning").html(""); $("#submitBtn").removeAttr("disabled"); } },"json"); } else { $("#submitBtn").attr("disabled","disabled"); } }); }); </script> </head>

<body>

<form name="mainForm"> New Artist: <input name="artist" id="artist"><br/> <div id="warning"></div> <input type="submit" id="submitBtn" value="Save" disabled="disabled"> </form>

</body> </html>

Outside of the code, the only other difference is in the HTML. Previously I made use of cfform, but since I'm not using any client-side code autogenerated from ColdFusion, I switched to vanilla HTML tags. The code block now loads in jQuery and adds a keyup listener to our artist form field. After I get the value - I either do my Ajax post or just disable the submit button. (Note - since this form has a single field it can still be submitted with an enter key. I'm not going to worry about that now.)

So it's not a lot more code at all. But you do have to handle the binding yourself. It's just one extra line of code though so it's nothing to worry about. You can demo this yourself here (remember to use "Weber" as an artist).