Retrieving Data via Ajax
Problem
I want to do a call and/or response to my server without causing the current page to refresh. For example, I might want to dynamically populate some content, or update a section of my page, or maybe check to see whether some text entered into a field is valid.
Solution
Ajax can be used for such a wide variety of uses that it would require a whole other book to run down all the various permutations and combinations (conveniently, you can pick up any number of O’Reilly books on the topic, including Understanding AJAX: Using JavaScript to Create Rich Internet Applications and Ajax for Web Developers). As a simple example, we’re going to use a text field in which users would enter the username they’d like to use, and then we’ll check on the fly to see whether it’s available. You’ll need a text input on your Canvas page:
<div id="registration">
<div id="usernameFields">
<label for="username">Username:</label>
<input type="text" id="username" onchange="checkUsername(this);" />
<span id="usernameAvailable"></span>
</div>
</div>The JavaScript for checkUsername() is surprisingly simple because of the Ajax object
provided by Facebook Platform, which really makes your life
easy:
function checkUsername(usernameField){ if(usernameField.getValue() == ''){ document.getElementById('usernameAvailable').setTextValue(''); return; } var encodedUsername = escape(usernameField.getValue()); var checkUsername = new Ajax(); checkUsername.responseType = Ajax.JSON; checkUsername.ondone ...