Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling Django View from Ajax

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");
        }
    })
}
like image 329
steph Avatar asked Sep 28 '22 02:09

steph


1 Answers

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

like image 54
chandu Avatar answered Oct 30 '22 00:10

chandu