Reputation: 165
I am new to Ajax and want to make an Ajax Request to a view function in Django with jQuery, but I am stuck.
I started with a simple example to check if it works
var button = $('.any_button');
$(button).click(function() {
var button_value = $(this).val();
$.ajax({
type: "POST",
url: "/url-path/to-my/view-function/",
dataType: "json",
data: { "button_value": button_value },
beforeSend: function () {
alert("Before Send")
},
success: function () {
alert("Success");
},
error: function () {
alert("Error")
}
});
});
I have inserted from https://docs.djangoproject.com/en/1.11/ref/csrf/
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;
}
var csrftoken = getCookie('csrftoken');
function csrfSafeMethod(method) {
// these HTTP methods do not require CSRF protection
return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
}
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
my view function:
from django.http import JsonResponse
def button_check(request):
data = {"message": "Message"}
return JsonResponse(data)
My url
path refers to views.button_check
I get the beforeSend alert
and the error alert
, but I expect the success alert
What did I miss? Unfortunately I am not able to go ahead.
Upvotes: 2
Views: 2080
Reputation: 39260
Your ajax setup is overwritten by values you pass to jQuery.ajax:
$.ajaxSetup({
beforeSend: function(xhr, settings) {
//this will never happen because it is overridden later
alert("you will never see this.");
}
});
$.ajax({
type: "GET",
url: "/index.html",
beforeSend: function () {
console.log("another before send");
},
})
.then(x => console.log("success:",x))
.then(undefined,reject => console.error(reject));
This means you won't authenticate and get the csrf token missing.
As you told in comments; remove the boforesend in $.ajax
Upvotes: 1
Reputation: 20137
in jquery try like this,
$.ajax({
type: "POST",
url: "/button_check/",
method: "POST",
data: { "button_value": button_value },
contentType: "application/json",
beforeSend: function () {
alert("Before Send")
},
success: function () {
alert("Success");
},
error: function () {
alert("Error")
}
});
url should be,
url(r'button_check/', 'views.button_check'),
if your request is "POST" or specific try,
def button_check(request):
if request.method == "POST":
data = {"message": "Message"}
return JsonResponse(data)
Upvotes: 2