Created
February 17, 2011 05:59
-
-
Save thinkt4nk/831085 to your computer and use it in GitHub Desktop.
ajax boilerplate
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$("a.ajax").live('click',function(e) { | |
e.preventDefault(); | |
var $this = $(this); | |
url = $(this).attr('href'); | |
$.get(url,function(data) { | |
if(data) { | |
if( $this.hasClass('addHtmlToParent') ) { | |
$this.parent().append(data); // append return content to parent | |
} else { | |
eval(data); // execute return js | |
} | |
} | |
else { | |
alert('Your request could not be processed at this time.'); | |
} | |
}); | |
}); | |
// forms | |
$("form.ajax").live('submit',function(e) { | |
e.preventDefault(); | |
var $this = $(this); | |
url = $(this).attr('action'); | |
postData = $(this).serialize(); | |
$.post(url,postData,function(data) { | |
if( data ) { | |
eval(data); | |
if( $this.parent().hasClass('hide') ) { | |
$this.parent().hide(); | |
} | |
} | |
else { | |
alert('Your request could not be processed at this time.'); | |
} | |
return false; | |
}); | |
}); | |
// for use with forms in forms | |
$('div.ajax-form input[type="submit"]').live('click',function(e) { | |
e.preventDefault(); | |
var $this = $(this); | |
var postData = {}; | |
var url = $(this).parent().attr('rel'); | |
$(this).parent().find('input').each(function() { | |
if( $(this).attr('type') !== 'submit' ) { | |
var name = $(this).attr('name'); | |
var value = $(this).val(); | |
postData[name] = value; | |
} | |
}); | |
$.post(url,postData,function(data) { | |
if( data ) { | |
eval(data); | |
} else { | |
alert('Your request could not be processed at this time.'); | |
} | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment