forked from jayallen/melody
-
Notifications
You must be signed in to change notification settings - Fork 36
DevGuide AJAX in Plugins
mikert edited this page Feb 11, 2011
·
1 revision
Movable Type, on which Melody is based, got its start well before AJAX became popular. Over the years, it's gotten some of its features rewritten to take advantage of AJAX, but a lot of developers don't see to be aware of how well its architecture can be leveraged to support AJAX. The featured image plugin is a good example of how to use Melody mode handlers to return JSON data structures to AJAXified JavaScript.
Here is an example mode handler which returns a list of the most recent entries:
sub _hdlr_ajax_get_recent_entries {
my $app = shift;
use JSON;
my @entries = MT->model('entry')->load({ blog_id => $app->blog->id }, { limit => 10 });
my @retval = map {
{
title => $_->title,
link => $_->permalink,
comment_count => $_->comment_count,
creator => MT->model('author')->load({ id => $_->created_by })->nickname
}
} @entries;
return JSON::to_json( \@retval );
}
The config.yaml setting to expose that would look like:
applications:
cms:
methods: mypluginname.ajax_get_recent: $MyPlugin::Plugin::_hdlr_ajax_get_recent_entries
From within a plugin, that can now be accessed like this:
<$mt:AdminCGIPath$><$mt:AdminScript$>?__mode=mypluginname.ajax_get_recent&blog_id=1
The result will be a JSON string that looks like:
[ { title: 'Latest Post', link: 'http://domain.com/2011/02/latest-post/', comment_count: 35, creator: 'John Smith'}, {...} ]
The client side looks like:
$.ajax({
url: '<$mt:AdminCGIPath$><$mt:AdminScript$>',
data: {
'__mode': 'mypluginname.ajax_get_recent',
'blog_id': '<$mt:var name="blog_id"$>'
}
}).success(function(data, status, xhr) {
try {
obj = eval('(' + data ')'); //JavaScript array
for (index = 0; index < obj.length; index++)
doSomething( obj[index] );
} catch (ex) {
alert(ex.message);
}
});