How To Create Form Posts with Ajax [con't]
Sending Queries As XMLHTTP
Requests
Sending the form submissions through Ajax is easy once the Post object has been created (and it can be reused for future forms). The Post
object consists of only four methods, Send
, OnResponse
, buildQuery
and getElementValue
, with each one being relatively self-explanatory. It all starts with the Send
method, which is added to the forms onSubmit
event, with the form element as its parameter. With this form element the Send
method calls buildQuery
. buildQuery
iterates through all of the forms elements, calls getElementValue
and builds a query string from each element name and value. Once the query string is constructed, the Ajax request is made by using the form method as the method of submission, the form action is the file that we make the request to, the query is the query that we just built and the callback method is OnResponse
, which writes the results to the page.
The Server-Side
The bridge file that we submit the form values to needs to accommodate both get
and post
methods. In order to do this we need to check whether one or the other is set and then handle the values as necessary. i.e., I've created a bridge.php
file to show you how you would handle the request and return a response as XML.
This is all it takes to convert your forms to Ajax. The object creation process takes a bit of time, but now you have a reusable way of handling form submissions with Ajax.
About The Author
Original: August 29, 2007