[Answered ]-Jquery function cannot send ajax request to django server

2👍

Well I created a gist but made it secret somehow (can I edit that?? lol). Anyway, you need to include the csrftoken in your post. Here is my answer:

    function getCookie(name) {
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }

You can use that getCookie function for any of your posts, just include it like so:

     $(document).ready(function() {
        $("#button").click(function(){
            $.ajax({
                type : "POST",
                url : "{% url 'getlist' %}",
                data : {
                    msg : 'abcd',
                    csrfmiddlewaretoken: getCookie('csrftoken')
                }
            }).done(function(data){
                alert(data.message);
            });
        });
    });

0👍

Read the ajax section on the django docs page on csrf.

Leave a comment