Using POST and XML in AJAX

In an earlier entry, Missing Data After AJAX Call, I threw a hack together to return multiple values which required parsing based on a separator on the client side.

After testing, I realized using a character as a separator is a bad idea. The data returned could have the character as part of its value and screw up the parsing later on the client side. Storing the data as XML and returning the data as such makes for a more elegant solution.

I also wanted to send a large amount of text through AJAX and the GET request was not getting the job done. Using POST instead of GET works well; the reason behind it is similar to why it works for forms or forum postings.

Talking about the what’s and why’s does not make it very clear. That is why I brought an example with me including the corresponding code. w00t!

On messageboards, the posting form usually has a preview button which directs the user to a new page to see how their post would look after submission. Upon submission, there may be a validation script that runs to check for missing fields or whatnot. Rather than reloading the page for each of these actions, we can use AJAX to do both at once!

The Plan:

  • User fills out form.
  • User clicks Preview button.
  • Click triggers call to JavaScript function.
  • Function retrieves form values.
  • Function sends values to PHP script.
  • PHP script returns an XML file.
  • Function parses XML file.
  • Function updates page on screen.
  • User rejoices.

Step 1: Create the form.

Add the function call on the preview button. This would also be a good time to add the preview and error divs for the returned data.