[Answer]-Submit form in JSON with AJAX


If using this Jquery cookies library, which is the one I was using and @Archer suggested me as well then you do need to get the cookies as $.cookie("cookie_name")

If you do it like that whole function is working and I get no errors when posting data with AJAX.
Also return false is enough for stopping the form to submit. event.preventDefault(); is not necessary.

The whole complete code then is:

                username = $(this).find("#id_username").val();
                password = $(this).find("#id_password").val();
                var arr = { "csrfmiddlewaretoken": $.cookie("csrftoken"), "username": username, "password": password};
                $.post("/myaccount/", arr,function(data){
                }, "json");
                return false;

Also, if you are including {% csrf_token %} in your HTML code then you can get the values from either the Cookie or the <input type="hidden" name="csrfmiddlewaretoken"> it creates in the form.



First, I think adding this line will prevent form from submitting while the function is computing:

    e.preventDefault(); // LINE ADDED
    /* treatment here */
    return false;

Furthermore, just to avoid mixing the CSRF token with your data, you can call the following function before using any Ajax request:

var csrftoken = getCookie('csrftoken');
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);


It’s happening because when you use getCookie it isn’t recognised as a function and therefore javascript stops running. You need to replace the call to getCookie with a function that does exist.

Use this library…


Change the following line of code to read…

var arr = { "X-CSRFToken": $.cookie("csrftoken"), "username": username, "password": password};

I’m assuming you’ve got the code from elsewhere and assumed getCookie is a valid function, when it isn’t.

Leave a comment