Pixelbox

Welcome to Pixelbox. Friday the 5 of September 2008

Skip to content >>

Efficient AJAX forms with prototype

In the past I have found posting forms via Ajax to be a pain in the ass. Mainly because you have to go through the DOM and get the values for each field and then pass them through to your AJAX target page as post or get variables.

Just recently I came up with a problem where by I needed to only perform an update if values have changed, as the action taken was quite complex and took a bit of time. Firstly I updated my PHP page to only perform the action if the class's values had changed. This was great but my front end had no idea of the PHP script's findings and consiquently didn't know how to react. Should it start looking as though it was doing to time comsuming update, or should it just do nothing?

With no way of knowing, my front end would start an animation as though it was waiting for the timely update but as it wasn't taking any time at all it would try and perform the finished animation too soon, resulting it a horrid looking car crash of an animation. I solved this by moving all new animations to the back of a queue () but it still didn't actually need any animations at all.

I then decided that in order to get my JavaScript in line with my PHP, I would need to do a client side check to detect changes to my form. In steps... Form.serialize(), using this function to quickly get the values of a form I could detect change just like with my PHP classes by performing a classic before and after comparison.

So when I first get my form using AJAX I quickly update a global variable with the results from Form.serialize($('the_id_of_your_form'). Then later when I am about to use AJAX to send my PHP script the new form values I perform the same function again into a new variable.

Now I have two variables with the contents of the form, both before and after allowing me to compare them and perform the AJAX call only if needed (as well as the subsquent animation effects).


// In the AJAX get form, on complete function do this: global_form_data = Form.serialize($('options_form')); (don't forget to set up the global variable outside your function first)

	function save_form_values() {	
			var pars = Form.serialize($('form'));
			if ( global_form_data != pars ){
			    // Enter AJAX call here with new values in the pars variable
			}
	}

Hope that helps someone out there! Find out more about Form.serialize() on the script.aculo.us Wiki

Meta tags: Ajax, Development, JavaScript

2 comments

Why not leave your own!

  1. nice tutorial . can u please tell me how i can POST a form using prototype framework
  2. hey jude, you could also do $('formElementID').request(); http://www.prototypejs.org/api/form/request

Add your own comment