Calling Django View from Ajax

10,093

Replace "post" with "ajax" in the code,now the print statement will work in your view.

function request_access($this){
    console.log("button clicked");
    var request_data = $this.id;
    console.log("data: " + request_data);
    $.ajax({
        url: "request_access/",
        data : { request_data: request_data},
        success : function(json) {
            $("#request-access").hide();
            console.log("requested access complete");
        }
    })
}

Difference between $.post and $.ajax?

$.post vs $.ajax

Share:
10,093
steph
Author by

steph

Updated on June 04, 2022

Comments

  • steph
    steph almost 2 years

    I'm using Ajax (along with Django) to perform some action on button click. I successfully call the javascript function but I can't call the Django view. There are no errors but the print statement in my view doesn't print...?

    urls.py

    urlpatterns = patterns('polls.views',
        url(r'^request_access/$', 'request_access',
            name='request_access'),
    )
    

    views.py

    def request_access(request):
        print("DJANGO VIEW")
        if request.method == "POST":
            print("DATA: ", request.POST.get('request_data'))
            return HttpResponse(
                json.dumps(response_data),
                content_type="application/json"
            )
    

    template.html

    <button class="btn btn-green btn-sm" onclick="request_access(this)" id="{{ data }}"><i class="fa fa-plus"></i> Join Group</button>
    

    javascript.js

    function request_access($this){
        console.log("button clicked");
        var request_data = $this.id;
        console.log("data: " + request_data);
        $.post({
            url: "request_access/",
            data : { request_data: request_data},
            success : function(json) {
                $("#request-access").hide();
                console.log("requested access complete");
            }
        })
    }