Saturday, December 18, 2010

Ajax.Request, Ajax.Updater, Callbacks

Ajax.Request sends data to an external program.
Ajax.Updater just like Ajax.Request but will update id tags on your page.

method:get - retrieve data from the external program.
method:post - to only send data to the program.

CALLBACK
You'll see "callback" used in tutorials. We have 3 pieces: the html form, the Javascript, and the external program. So, who is calling back what?

Per the jQuery folks, "a callback is a plain JavaScript function passed to some method as an argument or option."

In proper time, the method is calling back data or event from the function within the method. Think of a mother (method) calling the kids back home (function=callback) so that they can eat dinner (data or event).

In the following example,
  • The argument or option passed is the function in purple. 
  • This is passed onto the method, someMethod (made up - "someMethod" doesn't exist unless I program it to exist.).
  • Thus, the "callback" is the function(event) in purple.

$("body").someMethod(
 function(someFunction) {
   console.log("clicked: " + event.target);
 }

Events can be called back to give the user a chance to react when a certain state is triggered. jQuery's event system uses such callbacks everywhere:

$("body").click(
 function(event) {
   console.log("clicked: " + event.target);
 }
);

Arguments and a context can be within a callback.
Above, the callback is called with one argument, an event.
The context is set to the handling element, in the above example, document.body.

Callbacks can return data, either required or optional.

E.g., to prevent a form submission, a submit event handler can return false:

$("#myform").submit(
function() {
   return false;
 }
);

Instead of always returning false, the callback could check fields of the form for validity, and return false only when the form is invalid.
Thank you to the folks at jQuery for the above.

Where am I? 
I can return data and update one element on a page with the Ajax.Request method. How about passing several data from the external program to the page to update several different elements.

To do that, JSON will help me parse the data without learning the syntax of XML.

No comments:

Post a Comment