Skip to content

Instantly share code, notes, and snippets.

@HondoOhnaka
Created August 20, 2012 16:17
Show Gist options
  • Save HondoOhnaka/3405441 to your computer and use it in GitHub Desktop.
Save HondoOhnaka/3405441 to your computer and use it in GitHub Desktop.
Simple ajax submit for Django form (specifically admin save and continue editing), reference for handling CSRF Middleware
#via http://ankursethi.in/journal/2012/Aug/19/a-django-admin-wishlist/
# In ajax_submit.js.
# NOTE: I'm not very good at writing idiomatic JavaScript.
# If you think this snippet can be improved, do
# let me know.
# WARNING: this code is meant for demonstration purposes.
# Do not use it in production. It fails on several edge cases
# and, in the process, destroys your data, empties your bank
# account, kidnaps your children and takes down reddit for a
# month.
"use strict;";
var AJAXSubmit = function () {
if (!$) {
var $ = django.jQuery;
}
function ajax_submit(e) {
e.preventDefault();
var data = {
// Don't forget the CSRF middleware token!
"csrfmiddlewaretoken":
$("input[name='csrfmiddlewaretoken']").val(),
"title": $("textarea#id_title").val(),
"slug": $("input#id_slug").val(),
"author": $("select#id_author").val(),
"published_on_0": $("input#id_published_on_0").val(),
"published_on_1": $("input#id_published_on_1").val(),
"content": $("textarea#id_content").val()
};
if ($("input#id_published").is(":checked")) {
data["id_published"] = "on";
}
$.ajax({
type: "POST",
url: "",
data: data,
success: function() {
alert("Saved!");
}
});
return false;
}
$(document).ready(function() {
var btn = $("div.submit-row input[name='_continue']");
btn.click(ajax_submit);
});
}();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment