Use MochiKit Async for JSON based AJAX
MochiKit works well for doing AJAX stuff. Here's a loose idea of how to use it. Please note this illustration does not employ the Mischievous AJAX Method described in a previous post.
First, set up a page/controller/URL that, when accessed, returns a JSON string instead of HTML. To produce the JSON string you probably need a PHP library (or Python or whatever) to turn server-side data into JSON data. I'm not sure how to do that just yet in PHP but I'll tell you later when I figure it out. Once you get the PHP to serve a JSON object, the response string might look like this:
called URL with query params: http://localhost/bookdetails.php?book=[book title]
JSON response string: { 'author':'Mark Twain', 'book':'Tom Sawyer' }
If you go directly to the URL in the exhibit above your browser will probably spit out the JSON response string verbatim as just plain text. Now we look at the MochiKit code.
Take advantage of MochiKit to make your programming easier! MochiKit loadJSONDoc will create the proper URL for you when you pass in dictionaries.
// query arguments
var args = { book:'Tom Sawyer' };
// the url we're going to hit
var url = "http://localhost/bookdetails.php";
// setup a call to the url with its query params
var d = loadJSONDoc(url, args);
// the function inside will fire when the data comes back
d.addCallback(function (result) {
alert(result["author"]);
});
In this example the URL that loadJSONDoc calls evaluates out to be "http://localhost/bookdetails.php?book=Tom%20Sawyer"
The d.addCallback attaches a function that will fire once the request completes and the response is back. Notice that the value of result comes back automagically. That means in this example when you see an alert message come back that means the request completed. You decide what you do with success or failure by using addCallback and addErrback. If you want to have success and failure behaviors you can define both using addCallbacks -- notice the pluralization.
Nuts!
My ISP crashed and consequently went out of business. I have moved my blog. For new articles visit blog.infoentropy.com
tags in Articles
User login
Other blogs
Recent blog posts
- Step-by-step to build a facebook app with CakePHP
- Enabling CakePHP 1.1 on Lighttpd 1.5
- Install and configure PHP5 and lighttpd on mac os x 10.4
- lighttpd as a startup item on os x
- Mac tips for Unix users
- Moving your cursor in a terminal with bash shell (Mac OS X, and Ubuntu Linux compatible)
- linux user management commands
- Setup LigHTTPD virtual hosting by hand
- Reload your hosts file in Mac
- Using MochiKit doXHR
