AJAX Generic Form Parser – With Validation:
Okay, straight to the main JS code.
createXMLHttpRequest() – This is the function which will establish the AJAX connection object, this is called as soon as the JS file is loaded.
sendRequest() – This function is the one which is called when the form is submitted. This function requires (passed in) the ‘Form Object’ and the ‘File Name’ of the script which will receive the form data. When this function has been called, it takes the form object and passes it to the JS function getForm() which in turn parses the whole form extracting all the data. sendRequest() then takes the open AJAX connection and passes all the data to the PHP file form processing. Finally when the request from the PHP server script is returned, it writes out the reply to an element on the screen with the div ID ‘results’.
getForm() – This is the magic, this function reads through the whole form and extracts the field data before returning it back to sendRequest(). It handles radio, text, password, textarea, select and checkbox field types. It even looks for validation requests on text, password and textarea fields (which is enabled by using title=”required” in the form element).
Next is a very simple form with a mixture of field types and validation requests (nothing fancy here). Also included at the bottom is the div which prints out the results to the browser.
As you can see the form trigger which calls the AJAX actions is set in the button using the onClick method. Also note I’ve added title=”required” to the ‘textOne’ field – this means the user will not be able to submit the form unless this field contains a value.
Finally here is a very stripped down Server script in PHP which takes the form values and returns them formatted back to the JS (you could do anything with the data at this stage!).
You could easily change the above to generate an email or add the form data to a database, the above example will echo out the results which are passed back to the div tag below the form.
There you have it, short and sweet (I hope) – I’ve intentionally kept the example scripts to a minumum but with still enough to be useful. Please feel free to take this and mess around with it.