I have a form, which I use Text::MicroTemplate to add some fields to it, such as:
User Name
Last Name
Email
the fields are added using a loop inside a <form> tag, the data for these is validated using a regex (sent as a parameter to the template and “hidden” in the HTML in <span> tag with style display:none), so far, all is fine.
suddenly I have to add another field, for which the data has to be validated on the server side, what is the best approach for doing so? (I can of course, check the POST data, and if its incorrect, can send back the form with the relevant error message, but then, I will have to render the whole page again, which I dont do for the other fields…)
probably something with ajax?
thanks,
AJAX can avoid the whole page rendering which is a good thing™.
You know for sure that writing AJAX code working with different browser implementations, will lead to spaghetti-JavaScript-code, so my advice is to level differences with a good JavaScript library. I have chosen jQuery, because is easy to learn and fun to use if you alredy know CSS2 selectors. There there are other good libraries YUI, Prototype, MooTools, just choose one.
With jQuery, you can invoke an AJAX call in various ways including this simple version:
where
'html','text','xml','json', that tells what kind of response to expect from server.Usually, to send a form, you have to hook an event handler to the submit button: the event handler hijacks the submit event, giving the opportunity to validate values client-side and send them with an AJAX call.
I can understand that my example is oversimplifed, but that pattern is rather common: hijack-submit-event-and-do-it-another-way.
You’ll find more examples ( including those with powerful jQuery plugins ) in chapter 11 of jQuery Cookbook, entitled Html form enhancements with plugins.