‘There can only be one’
★ Nice take on the ‘There can only be one’ NBA ads.
★ Nice take on the ‘There can only be one’ NBA ads.
★ Validating user input data is an essential requirement for building robust and secure web applications. Validation generally isn’t a developer’s favorite part of coding, but it is very necessary. A web application that doesn’t validate user data properly can result in a poor user experience, a large overhead of useless data in your database, and vulnerability to malicious SQL injection attacks.
There are basically two approaches to validation, client-side and server-side. There are drawbacks to both methods.
◦ Server-side validation is limited by the stateless nature of the http protocol. When an invalid data error is caught the page is reloaded again, forcing you to send all submitted data back to populate the form or make the user re-input the entire form.
◦ When submitting the page, the user needs to wait for a full page reload. This roundtrip is repeated for every mistake that the user makes. This is a very inefficient model.
◦ Javascript validation can help remedy this by checking user data before the form even gets submitted. While this would help to improve the user experience it cannot be relied on because javascript is not necessarily standard across all browsers. Also javascript can easily be disabled in the browser’s settings.
Traditionally developers would leverage both client and server-side to offset the failures of each. This is fine except it means that you need to double code everything making you work harder than you need to. Using Ajax you can get the best of both worlds, keeping your stable/reliable php validation class as your backbone without sacrificing a responsive user-friendly UI. Most importantly it will degrade gracefully.
Here we hijack the form submit in an onload function and submit the data asynchronously via ajax then set a callback. In this particular example I used the jQuery.js library, but the same thing could be done with prototype.js or your own ajax engine. I prefer prototype.js but I chose to use jquery.js because the facebook style lightbox modal feedback that I use requires jQuery.js already.
Once the data is passed to your php controller you can validate and sanitize it however you please. On the server side nothing really has to change too much, with the exception of how you handle the feedback/results. The beauty of this method is the way it gracefully degrades. If the user has javascript disabled, the form will still get submitted and the validation will be handle exactly the same either way.