Skip to content

Instantly share code, notes, and snippets.

@muayyad-alsadi
Created December 31, 2013 15:02
Show Gist options
  • Save muayyad-alsadi/8198060 to your computer and use it in GitHub Desktop.
Save muayyad-alsadi/8198060 to your computer and use it in GitHub Desktop.
declatative-ajax.js
function ajax_load(e){
// styled after bootstrap-ajax < https://github.com/eldarion/bootstrap-ajax
var $e=$(e), src=e.getAttribute('data-src'), data={};
var s,k,$target,f;
var verb=e.getAttribute('data-verb');
if (!verb) verb='get';
if (e.getAttribute('data-params')) {
$.extend(data, $.parseJSON(e.getAttribute('data-params')) );
}
$.ajax({type:verb, url:src,data:data, dataType:'json',
/*
beforeSend: function() {$('body').modalmanager('loading')},
complete: function(){$('body').modalmanager('loading')},
*/
success:function(d){
// return something like this {fragments:[{'#results':{html:'<b>hello</b>'}, '.container':{closest:true, prepend:'new'}}]}
for(s in d.fragments) {
f=d.fragments[s];
if (f.closest) $target=$e.closest(s);
else $target=$(s);
if (f.text) $target.text(f.text);
if (f.html) $target.html(f.html);
if (f.append) {
$target.append(f.append);
}
if (f.prepend) $target.prepend(f.prepend);
if (f.attr) {
for(k in f.attr) $target.attr(k, f.attr[k]);
}
if (f=='refresh' || f.refresh) $target.load($target.attr('data-refresh-url'));
if (f=='remove' || f.remove) $target.remove();
}
}
});
}
$(document).on('click', '[data-toggle="ajax-load"]', function(){ajax_load(this)});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment