Answer the question
In order to leave comments, you need to log in
Django ajax problem?
There is a form
<form class="f-basket" action="{% url 'add_basket' %}">{% csrf_token %}
Сколько?
<input type="number" class="number">
<button type="submit" class="submit_btn" data-text = "Здесь просто текст">Отправить</button>
</form>
$(document).ready(function(){
var form = $('.f-basket');
form.on('submit', function(preventdefault){
preventdefault.preventDefault();
var submit_btn = $('.submit_btn');
var text = submit_btn.data("text")
var nmb = $('.number').val();
console.log(text, nmb)
var data = [];
data.text = text
data.nmb = nmb;
var csrf_token = $('.f-basket [name="csrfmiddlewaretoken"]').val();
data["csrfmiddlewaretoken"] = csrf_token;
var url = form.attr("action");
console.log(url)
console.log(data)
$.ajax({
url: url,
type: 'POST',
data: data,
cache: true,
success: function () {
console.log("OK");
},
error: function(){
console.log("error");
}
})
$('.basket-container ul').append('<li>'+text+ ' в количестве '+ nmb +
'<a class="delete-item" href="#">x</a>'+ '</li>');
});
$(document).on('click', '.delete-item', function(preventdefault){
preventdefault.preventDefault();
$(this).closest('li').remove();
})
});
def add_basket(request):
return_dict = dict()
session_key = request.session.session_key
if not session_key:
request.session.cycle_key()
print(request.POST)
return JsonResponse(return_dict)
Answer the question
In order to leave comments, you need to log in
The documentation has a whole section about it .
$.ajaxSetup({
beforeSend: function(xhr, settings) {
if (!csrfSafeMethod(settings.type) && !this.crossDomain) {
xhr.setRequestHeader("X-CSRFToken", csrftoken);
}
}
});
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question