views:

36

answers:

2

Our webapp has a form with fields and values that change depending on values entered. Each time there is a change event on one of the form elements, we use an expensive AJAX call to update other elements on the page.

This works great for selects, radio buttons and checkboxes. The issue comes in when a user adds content to a text field, and then clicks a link without taking the focus from the text field. The browser moves to a new page, and the contents of the text field are never saved. Is there an easy way to code around this? The AJAX call is too expensive to call with each key press.

Here's an example of my Prototype code at the moment:

$$('.productOption input.text').invoke('observe', 'change', saveChangeEvent);
A: 

Have you considered hooking into the window unload() event? Here is a c/p jQuery example using .unload().

$(window).unload(function() {
  var input = $("#MyInput");  // Text field to check for

  if(input.length > 0)
  {
     //Ajax call to save data, make sure async:false is set on ajax call.
  }
});

This lets you work around making a call on each key press, by making one if they leave the page.

Zachary
How could that tell me which field to update with an AJAX call?
Eric the Red
easy. keep a variable called lastEditedField that is set through the keydown event on an input field
seanizer
hopefully that makes more sense... just check the value when leaving the page and then make 1 ajax call to save the value...
Zachary
This does technically work if asynchronous:false, but then a progress indicator can't be displayed.
Eric the Red
A: 

using prototype, you can have a PeriodicExecuter listen while you're typing and sending off an ajax query when nothing has happened for e.g. 2 seconds and value has changed since the last AJAX request. Start the executor using a focus event and shut it down using a blur event, that way you only need one executor at a time

seanizer
Unfortunately the AJAX request would be too disruptive if the user wasn't actually finished.
Eric the Red
really? that would suggest that either that the server code is extremely slow or you are doing way too much on the client. Search sites everywhere are using ajax-autocompletion without interfering with the user experience in a negative way.
seanizer
Yes, the server code is extremely slow. The app needs to call an external service that we have no control over.
Eric the Red