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");
}
})
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With