Created
July 18, 2013 22:41
-
-
Save stvbdn/6033742 to your computer and use it in GitHub Desktop.
AJAX - Django & jQuery
This file contains hidden or 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
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