[Answer]-Submit form in JSON with AJAX

1👍

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:

$(function(){
            $("#acc").submit(function(){
                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){
                    alert(data.test);
                }, "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.

👤zurfyx

0👍

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

$("#acc").submit(function(e){
    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');
$.ajaxSetup({
    crossDomain: false, // obviates need for sameOrigin test
    beforeSend: function(xhr, settings) {
        if (!csrfSafeMethod(settings.type)) {
            xhr.setRequestHeader("X-CSRFToken", csrftoken);
        }
    }
});

0👍

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…

https://github.com/carhartl/jquery-cookie/blob/master/jquery.cookie.js

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