Skip to content

Instantly share code, notes, and snippets.

@stvbdn
Created July 18, 2013 22:41
Show Gist options
  • Save stvbdn/6033742 to your computer and use it in GitHub Desktop.
Save stvbdn/6033742 to your computer and use it in GitHub Desktop.
AJAX - Django & jQuery
Here's a shitty example of using AJAX in Django. Serialize your form before you pass it through the data variable.
<script type="text/javascript">
$('#form-delete').on("submit", function(e) {
e.preventDefault()
// Use AJAX to delete the comment.
comment = $(this).attr('data-comment');
$.ajax({
type: 'POST',
url: $(this).attr('action'),
data: {'csrfmiddlewaretoken': '{{csrf_token}}'},
success: function(data) {
// Hide comment that was just deleted
$(comment).hide();
},
error: function(data) {
console.log('Something went wrong');
},
});
//return false;
})
</script>
def delete_comment(request, pk):
if request.is_ajax():
try:
comment = Comment.objects.get(id=pk)
comment.delete()
except:
pass
return HttpResponse("Success")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment