Getting Error while deleting Cart item using DestroyAPIView with Javascript. (Django) - javascript

I'm using DestroyAPIView with Javascript to delete the cart item in Django
While clicking on delete button it shows the following error on chrome console:
jquery.min.js:2 DELETE http://127.0.0.1:8000/showdata/2342; 404 (Not Found)
send # jquery.min.js:2
ajax # jquery.min.js:2
destoryCart # (index):46
onclick # (index):1
(index):55 {readyState: 4, getResponseHeader: ƒ, getAllResponseHeaders: ƒ, setRequestHeader: ƒ, overrideMimeType: ƒ, …}
and in vs code terminal showing:
Not Found: /showdata/2342;
and all my code goes here:
views.py
class CartDestroyAPIView(DestroyAPIView): # DeleteView
permission_classes = [IsAuthenticated] # Or anything else you want
authentication_classes = [SessionAuthentication] # Or anything else you want
serializer_class = productserializers
queryset = Cart.objects.all()
index.html
<script>
$(document).ready(function() {
$.ajax({
url: 'http://127.0.0.1:8000/showdata ',
dataType: 'JSON',
success: function(data){
for (var i = 0; i < data.length; i++)
{
var row =
$('<tr><td style="font-style:bold">'
+data[i].product.name+'</td><td style="font-style:bold">'
+data[i].product.price+'</td><td><a href='
+data[i].product.link_href+'><button type="button" class="btn btn-outline-success">Buy</button></a></td><td><button onclick="destoryCart('+data[i].product.id+')" type="button" class="btn btn-outline-danger">DELETE</button></td></tr>');
$("#tableProduct").append(row);
}
}
});
});
const destoryCart = (id) => {
let url = `http://127.0.0.1:8000/showdata/${id};`
$.ajax({
beforeSend: function(xhr){xhr.setRequestHeader('X-CSRFToken', "{{ csrf_token }}");
},
url: url,
type: 'DELETE',
success: (data) => {
console.log("deleted!");
},
error: (err) => {
console.log(err);
}
});
};
</script>
urls.py
path('cart_destroy/<int:pk>', views.CartDestroyAPIView.as_view(), name ='cart_destroy'),
WHAT IS WRONG GOING WITH THIS CODE.

Change your URL in ajax call you have to put this URL in side your destoryCart()
let url = `http://127.0.0.1:8000/cart_destroy/${id};`
instead of this URL http://127.0.0.1:8000/showdata/${id};
UPDATE
get csrf_token like this i don't know if there is another way but as per official doc.
function getCookie(name) {
let cookieValue = null;
if (document.cookie && document.cookie !== '') {
const cookies = document.cookie.split(';');
for (let i = 0; i < cookies.length; i++) {
const cookie = cookies[i].trim();
// 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;
}
const csrftoken = getCookie('csrftoken');
And you ajax call
const destoryCart = (id) => {
$.ajax({
type: 'POST',
url: "{% url 'cart_destroy' %}",
data: {
'product_id': id,
'csrfmiddlewaretoken': csrftoken,
},
success: function(success) {
console.log('success : '+success.responseText)
},
error: function(error) {
console.log('error : '+error.responseText)
},
});
}
and you have to update your URL also like this
path('cart_destroy/', views.CartDestroyView, name ='cart_destroy'),
add this in your views.py
def CartDestroyView(request):
if request.method == "POST":
product_id = request.POST['product_id']
Cart.objects.filter(id=product_id).delete()
return HttpResponse({'Success':"Deleted Successfully."})

Related

update function failing, create & delete working

I can create, delete and display all but the update function will not work and does nothing. When I look the error in the console log it points to
jquery.min.js:2 PUT http://localhost:5000/shop/9 400 (BAD REQUEST)
send # jquery.min.js:2
ajax # jquery.min.js:2
updateServer # index.html:133
doUpdate # index.html:129
onclick # index.html:35
index.html:147
I cant see where I am going wrong. Am I missing something or is it within the update server code? This is the html code. A lot of the code for the update server is taken from other places within the html which works fine.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<title> View Shopping List</title>
</head>
<body>
<h1>Shop</h1>
<div id="create-update" style="display:none">
<h2>create-edit</h2>
<table id="createUpdateForm">
<tr>
<td>ID</td>
<td><input type="hidden" name="ID" id="idInput"></td>
</tr>
<tr>
<td>Dept</td>
<td><input type="text" name="Dept"></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="Name"></td>
</tr>
<tr>
<td>Amount</td>
<td><input type="text" name="Amount"></td>
</tr>
<tr>
<td></td><td>
<button id="create-button" onclick="doCreate()">Create</button>
<button id="update-button" onclick="doUpdate()">update</button>
</td>
</tr>
</table>
</div>
<div id="display">
<h2>Shop</h2>
<button onClick="showCreate()">Create</button>
<table id="shopTable" class="table">
<tr>
<th>ID</th><th>Dept</th><th>Name</th><th>Amount</th><th></th><th></th>
</tr>
</table>
</div>
JS:
function showCreate() {
document.getElementById('display').style.display = "none"
document.getElementById('update-button').style.display = "none"
document.getElementById('create-button').style.display = "block"
document.getElementById('create-update').style.display = "block"
}
function showUpdate(thisElem) {
var rowElement = thisElem.parentNode.parentNode;
shop = readShopFromRow(rowElement)
populateForm(shop)
document.getElementById('display').style.display = "none"
document.getElementById('update-button').style.display = "block"
document.getElementById('create-button').style.display = "none"
document.getElementById('create-update').style.display = "block"
}
function readShopFromRow(rowElement) {
shop = {}
shop.ID = rowElement.getAttribute("ID");
shop.Dept = rowElement.cells[1].firstChild.textContent
shop.Name = rowElement.cells[2].firstChild.textContent
shop.Amount = rowElement.cells[3].firstChild.textContent
return shop
}
function populateForm(shop) {
var form = document.getElementById('createUpdateForm')
form.querySelector('input[name="ID"]').value = shop.ID
form.querySelector('input[name="ID"]').disabled = true
form.querySelector('input[name="Dept"]').value = shop.Dept
form.querySelector('input[name="Name"]').value = shop.Name
form.querySelector('input[name="Amount"]').value = shop.Amount
}
function clearForm() {
var form = document.getElementById('createUpdateForm')
form.querySelector('input[name="ID"]').value = ''
form.querySelector('input[name="ID"]').disabled = false
form.querySelector('input[name="Dept"]').value = ''
form.querySelector('input[name="Name"]').value = ''
form.querySelector('input[name="Amount"]').value = ''
}
function doCreate() {
console.log("in doCreate")
shop = getShopFromForm()
console.log(shop)
$.ajax({
url: "/shop",
data: JSON.stringify(shop),
method: "POST",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result)
addShopToTable(shop)
showDisplay()
clearForm()
},
error: function(xhr, status, error) {
console.log("error" + error)
}
})
}
function doUpdate() {
shop = getShopFromForm()
updateServer(shop)
}
function updateServer(shop) {
$.ajax({
url: "/shop/" + shop.ID,
data: JSON.stringify(shop),
method: "PUT",
dataType: "JSON",
contentType: "application/json; charset=utf-8",
success: function(result) {
console.log(result)
updateTableRow(shop)
showDisplay()
clearForm()
},
error: function(xhr, status, error) {
console.log("error" + error)
}
})
}
function doDelete(thisElem) {
var tableElement = document.getElementById('shopTable');
var rowElement = thisElem.parentNode.parentNode;
var index = rowElement.rowIndex;
ID = rowElement.getAttribute("id");
$.ajax({
url: "/shop/" + ID,
method: "DELETE",
dateType: "JSON",
success: function(result) {
tableElement.deleteRow(index);
},
error: function(xhr, status, error) {
console.log(error)
}
})
}
function updateTableRow(shop) {
rowElement = document.getElementById(shop.ID)
rowElement.cells[1].firstChild.textContent = shop.Dept
rowElement.cells[2].firstChild.textContent = shop.Name
rowElement.cells[3].firstChild.textContent = shop.Amount
//console.log("updating table")
}
function getShopFromForm() {
var form = document.getElementById('createUpdateForm')
var shop = {}
shop.ID = form.querySelector('input[name="ID"]').value
shop.Dept = form.querySelector('input[name="Dept"]').value
shop.Name = form.querySelector('input[name="Name"]').value
shop.Amount = form.querySelector('input[name="Amount"]').value
//console.log(shop)
return shop
}
function showDisplay() {
document.getElementById('display').style.display = "block"
document.getElementById('create-update').style.display = "none"
}
function populateTable() {
//ajax getAll
$.ajax({
url: 'http://127.0.0.1:5000/shop',
method: 'GET',
datatype: 'JSON',
success: function(results) {
for (shop of results) {
addShopToTable(shop)
}
},
error: function(xhr, status, error) {
console.log("error " + error + " code:" + status)
}
})
}
function addShopToTable(shop) {
//console.log("working so far")
tableElem = document.getElementById("shopTable")
rowElem = tableElem.insertRow(-1)
rowElem.setAttribute("ID", shop.ID)
cell1 = rowElem.insertCell(0)
cell1.innerHTML = shop.ID
cell2 = rowElem.insertCell(1)
cell2.innerHTML = shop.Dept
cell3 = rowElem.insertCell(2)
cell3.innerHTML = shop.Name
cell4 = rowElem.insertCell(3)
cell4.innerHTML = shop.Amount
cell5 = rowElem.insertCell(4)
cell5.innerHTML = '<button onclick="showUpdate(this)">Update</button>'
cell6 = rowElem.insertCell(5)
cell6.innerHTML = '<button onclick="doDelete(this)">delete</button>'
}
populateTable()
Server API
from flask import Flask, jsonify, request, abort, make_response, url_for, render_template, redirect #https://blog.miguelgrinberg.com/post/the-flask-mega-tutorial-part-ii-templates Render template takes template and returns actual values
from flask_cors import CORS
from ShoppingDAO import ShoppingDAO
#from userinput import userinput
app = Flask(__name__,
static_url_path='',
static_folder='staticpages')
CORS (app)
#app.route('/')
def hello_world():
return 'Hello World'
# curl http://127.0.0.1:5000/
#app.route('/shop')
def getAllShop():
return jsonify(ShoppingDAO.getAllShop())
# curl http://127.0.0.1:5000/shop
# find By dept
#app.route('/shop/<string:Dept>', methods =['GET'])
def findShopByDept(Dept):
return jsonify(ShoppingDAO.findShopByDept(Dept))
# curl http://127.0.0.1:5000/shop/Spud
# find By ID
##app.route('/shop/<int:ID>')
#def findShopByID(ID):
# return jsonify(ShoppingDAO.findShopByID(ID))
# curl http://127.0.0.1:5000/shop/1
#app.route('/shop/<int:ID>', methods =['GET'])
def findShopByID(ID):
foundShop = ShoppingDAO.findShopByID(ID)
return jsonify(foundShop)
# Create
#app.route('/shop', methods=['POST'])
def createShop():
if not request.json:
abort(400)
if not 'ID' in request.json:
abort(400)
Shop={
"Dept": request.json['Dept'],
"Name":request.json['Name'],
"Amount":request.json['Amount']
}
values = (Shop['Dept'], Shop['Name'], Shop['Amount'])
newId = ShoppingDAO.createShop(values)
Shop['ID'] = newId
return jsonify(Shop)
# curl -X POST -d "{\"ID\":1, \"Dept\":\"Fresh\", \"Name\":\"Test\", \"Amount\": 5}" -H Content-Type:application/json http://127.0.0.1:5000/shop
#app.route('/shop/<int:ID>', methods=['PUT'])
def updateShop(ID):
foundShop = ShoppingDAO.findShopByID(ID)
if not foundShop:
abort(404)
if not request.json:
abort(400)
reqJson = request.json
if 'Amount' in reqJson and type(reqJson['Amount']) is not int:
abort(400)
if 'Dept' in reqJson:
foundShop['Dept'] = reqJson['Dept']
if 'Name' in reqJson:
foundShop['Name'] = reqJson['Name']
if 'Amount' in reqJson:
foundShop['Amount'] = reqJson['Amount']
values = (foundShop['Dept'],foundShop['Name'],foundShop['Amount'],foundShop['ID'])
ShoppingDAO.updateShop(values)
return jsonify(foundShop)
# curl -X PUT -d "{\"Dept\":\"Monday\", \"Name\":\"Mondy\", \"Amount\": 50}" -H Content-Type:application/json http://127.0.0.1:5000/shop/3
# Delete
#app.route('/shop/<int:ID>' , methods=['DELETE'])
def deleteShop(ID):
ShoppingDAO.deleteShop(ID)
return jsonify({"done":True})
# curl -X DELETE http://127.0.0.1:5000/shop/2
if __name__ == '__main__' :
app.run(debug= True)
The value property is a string, so the test type(reqJson['Amount']) is not int is succeeding and you're reporting an error.
Convert the amount to an integer when creating the JSON:
shop.Amount = parseInt(form.querySelector('input[name="Amount"]').value)

How can I get response ajax correctly?

I am learning C# and jQuery AJAX. I'm currently having a problem where I cannot get Ajax to run correctly and I am not sure why.
Here is the error log:
Failed to load resource: the server responded with a status of 500 (Internal Server Error)
Here is my code:
HTML
<button class="btn btn-primary btn-edit" id="{{SubjectId}}" id1="
{{StudentId}}" >Edit</button>
JavaScript AJAX code:
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!")
}
},
Error: function (err) {
console.log(err);
}
});
},
And ExamsController
[HttpGet]
public JsonResult LoadDetail(int id, int id1)
{
bool status = false;
Exam exam = new Exam();
exam = db.Exams.Find(id, id1);
status = true;
return Json(new
{
data = exam,
status = status
}, JsonRequestBehavior.AllowGet);
}
Internal server error means you have error in C# script, please double check error logs.
And also your code isnt cleanest, missing semi-colons.
Try add semi-colons, add name to function , and check error log, it can be useful, we can make better answer.
Maybe try this code with semi colon :) :
$('.btn-edit').off('click').on('click', function () {
$('#editModal').modal('show');
var id = parseInt($(this).attr('id'));
var id1 = parseInt($(this).attr('id1'));
ExamsController.LoadDetail(id, id1);
});
LoadDetail: function (id, id1) {
$.ajax({
url: '/Exams/LoadDetail',
type: 'GET',
data: {
id : id,
id1 : id1
},
dataType: 'json',
success: function (response) {
console.log(response.status);
if (response.status == true) {
var data = response.data;
$('#txtSubjectName').val(data.Subject.SubjectName);
$('#txtStudentName').val(data.Student.StudentName);
$('#numScore').val(data.Score);
} else {
alert("Error!");
}
},
Error: function (err) {
console.log(err);
}
});
},
Thanks!

Save multiple table rows with one save button in javascript

I am using the following code to save a row in a datatable using a save button
$(document).on('click','.updateOrder', function(){
var thisRow = $(this).closest('tr');
var rejectReasons = { PersistRejectReasons :[] }
var jsonReturnObj = new Object();
jsonReturnObj.OrderNumber = thisRow.find('.dt_orderNo').text();
jsonReturnObj.OrderLineNumber = thisRow.find('.dt_orderLineNo').text();
jsonReturnObj.RejectReasonCode = thisRow.find('.dt_researchOutcome').find("option:selected").prop("value");
jsonReturnObj.RejectReasonNotes = thisRow.find('.dt_researchNotes').find('input').val();
if(jsonReturnObj.RejectReasonCode != "" && jsonReturnObj.RejectReasonCode != null) {
if(jsonReturnObj.RejectReasonCode =="14. Other") {
if(jsonReturnObj.RejectReasonNotes == "" || jsonReturnObj.RejectReasonNotes == "null") {
alert(" Please add Research Notes");
jsonReturnObj.Processed = false;
$('#orderReportTable').append("call failed");
throw new Exception("Error message");
}
}
jsonReturnObj.Processed = true;
}else {
jsonReturnObj.Processed = false;
}
if($("#movedInput"+jsonReturnObj.OrderNumber+"-"+jsonReturnObj.OrderLineNumber).is(':checked')){
jsonReturnObj.IsAvailable = false;
}else{
jsonReturnObj.IsAvailable = true;
}
rejectReasons.PersistRejectReasons.push(jsonReturnObj);
var jsonReturnString = JSON.stringify(rejectReasons);
console.log("Rejecting Store Number is "+$("#storeNum").val())
var request2 = $.ajax({
headers: {
'RejectingStoreNum': $("#storeNum").val(), //thisRow.find('.dt_storeNo').text(), //thisRow.find("td").eq(16).text(),
'Content-Type': 'application/json'
},
type: "POST",
url: "persistStoreResearchOutcome", // REST endpoint. replace url1 with REST Endpoint
data : jsonReturnString,//json data. use data and contentType attributes for POST requests.
contentType: "application/json",
dataType: "text",
/*xhrFields: {
'withCredentials': true //Tell browser to provide credentials
},*/
crossDomain: true,// this is for cross domain requests*/
success: function (data, status, jqXHR){
console.log("status:"+status);
$('#orderReportTable').append("call successful");
if(jsonReturnObj.Processed){
thisRow.find('.dt_itemStatus').text("Researched");
table.draw();
}else{
thisRow.find('.dt_itemStatus').text("Active");
table.draw();
}
},
error: function (jqXHR, status, errorThrown){
//console.log("failed: status:"+status);
$('#orderReportTable').append("call failed, error"+errorThrown);
alert("There was an error while trying to save this item");
}
});
});
I want to do the same processing but for all the rows in the table with one single click.I used the each function to loop over the rows but keep getting an error
$("table tr").each(function (){
console.log(this);
var thisRow = $(this).closest('td');
var rejectReasons = { PersistRejectReasons :[] }
var jsonReturnObj = new Object();
jsonReturnObj.OrderNumber = thisRow.find('.dt_orderNo').text();
jsonReturnObj.OrderLineNumber = thisRow.find('.dt_orderLineNo').text();
jsonReturnObj.RejectReasonCode = thisRow.find('.dt_researchOutcome').find("option:selected").prop("value");
jsonReturnObj.RejectReasonNotes = $(this).find('.dt_researchNotes').find('input').val();
if(jsonReturnObj.RejectReasonCode != "" && jsonReturnObj.RejectReasonCode != null) {
if(jsonReturnObj.RejectReasonCode =="14. Other") {
if(jsonReturnObj.RejectReasonNotes == "" || jsonReturnObj.RejectReasonNotes == "null") {
alert(" Please add Research Notes");
jsonReturnObj.Processed = false;
$('#orderReportTable').append("call failed");
throw new Exception("Error message");
}
}
jsonReturnObj.Processed = true;
}else {
jsonReturnObj.Processed = false;
}
if($("#movedInput"+jsonReturnObj.OrderNumber+"-"+jsonReturnObj.OrderLineNumber).is(':checked')){
jsonReturnObj.IsAvailable = false;
}else{
jsonReturnObj.IsAvailable = true;
}
rejectReasons.PersistRejectReasons.push(jsonReturnObj);
var jsonReturnString = JSON.stringify(rejectReasons);
console.log("Rejecting Store Number is "+$("#storeNum").val())
var request2 = $.ajax({
headers: {
'RejectingStoreNum': $("#storeNum").val(), //thisRow.find('.dt_storeNo').text(), //thisRow.find("td").eq(16).text(),
'Content-Type': 'application/json'
},
type: "POST",
url: "persistStoreResearchOutcome", // REST endpoint. replace url1 with REST Endpoint
data : jsonReturnString,//json data. use data and contentType attributes for POST requests.
contentType: "application/json",
dataType: "text",
/*xhrFields: {
'withCredentials': true //Tell browser to provide credentials
},*/
crossDomain: true,// this is for cross domain requests*/
success: function (data, status, jqXHR){
console.log("status:"+status);
// $('#orderReportTable').append("call successful");
if(jsonReturnObj.Processed){
this.find('.dt_itemStatus').text("Researched");
table.draw();
}else{
this.find('.dt_itemStatus').text("Active");
table.draw();
}
},
error: function (jqXHR, status, errorThrown){
//console.log("failed: status:"+status);
$('#orderReportTable').append("call failed, error"+errorThrown);
alert("There was an error while trying to save this item");
}
});
});
});
How can I fix this?
The error message is
http://localhost:8080/persistStoreResearchOutcome 500 ()
send # jquery-3.2.1.min.js:4
ajax # jquery-3.2.1.min.js:4
(anonymous) # (index):544
each # jquery-3.2.1.min.js:2
each # jquery-3.2.1.min.js:2
(anonymous) # (index):509
dispatch # jquery-3.2.1.min.js:3
q.handle # jquery-3.2.1.min.js:3
I tried different ways to loop over the table including the every() function from datatables,but keep getting the same error

detail: "CSRF Failed: CSRF token missing or incorrect."

I have used window.CSRF_TOKEN = "{{ csrf_token }}" inside script tag in restaurant_detail.html where my react page for posting review is rendered. I am getting an error, though. In my onSubmit function i have consoled to check if csrf token is passed or not and yes it is.
my axios code for posting review is
onSubmit(props){
console.log('csrf',CSRF_TOKEN);
axios({
method:'POST',
url:'/api/review/create/',
headers:{
'X-CSRF-Token':CSRF_TOKEN,
//'Access-Control-Allow-Origin':'*',
'Accept': 'application/json',
'Content-Type': 'application/json',
},
data:{
review:props.review
}
})
.then(response => {
console.log('success');
})
.catch(error => {
throw("Error: ",error);
});
}
api/Views.py
class ReviewCreateAPIView(CreateAPIView):
queryset = Review.objects.all()
# permisssion_classes = [IsAuthenticated]
def get_serializer_class(self):
model_type = self.request.GET.get('type')
slug = self.request.GET.get('slug')
parent_id = self.request.GET.get('parent_id')
return create_review_serializer(model_type=model_type, slug=slug, parent_id=parent_id, reviewer=self.request.user)
serializers.py
def create_review_serializer(model_type='restaurant',slug=None, parent_id=None, reviewer=None):
class ReviewCreateSerializer(ModelSerializer):
class Meta:
model = Review
fields = ('id','review','created',)
def __init__(self, *args, **kwargs):
self.model_type = model_type
self.slug = slug
self.parent_obj = None
if parent_id:
parent_qs = Review.objects.filter(id=parent_id)
if parent_qs.exists() and parent_qs.count() == 1:
self.parent_obj = parent_qs.first()
return super(ReviewCreateSerializer, self).__init__(*args, **kwargs)
def validate(self, data):
model_type = self.model_type
model_qs = ContentType.objects.filter(model=model_type)
if not model_qs.exists() or model_qs.count() != 1:
raise ValidationError('This is not a valid content type')
SomeModel = model_qs.first().model_class()
obj_qs = SomeModel.objects.filter(slug=self.slug) # Restaurant.objects.filter(slug=self.slug)
if not obj_qs.exists() or obj_qs.count() != 1:
raise ValidationError('This is not a slug for this content type')
return data
def create(self, validated_data):
review = validated_data.get('review')
print('review',review)
if reviewer:
main_reviewer = reviewer
else:
main_reviewer = User.objects.all().first()
model_type = self.model_type
slug = self.slug
parent_obj = self.parent_obj
review = Review.objects.create_for_model_type(model_type, slug, review, main_reviewer, parent_obj=parent_obj)
return review
return ReviewCreateSerializer
urls.py
url(r'^create/$', ReviewCreateAPIView.as_view(), name="reviewcreateapiview"),
restaurant_detail.html
<div id="app"></div>
<script type="text/javascript"> window.CSRF_TOKEN = "{{ csrf_token }}"; </script>
How can i resolve this?
You have done a simple error. There is a typo. Do replace
'X-CSRF-Token'
to
'X-CSRFToken'
if you have code correctly, then it should post your data.
I'm not familiar with axios,but I solved a similar problem use the blow code with JQuery:
$.ajaxSetup({
data : {
csrfmiddlewaretoken : '{{ csrf_token }}'
},
});
you have to set the header in ajax call with cookie values.
$.ajaxSetup({
beforeSend: function(xhr, settings) {
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;
}
if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
// Only send the token to relative URLs i.e. locally.
xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
}
}
});

django ajax call return 403 bad request

I'm trying to compile project https://github.com/kannan4k/django-carpool
please refer this project repo for this issue.
and end up with following error during ajax call.
Failed to load resource: the server responded with a status of 400 (BAD REQUEST).
I know this is because of ajax post request & CSRF tokens.
following is my setting.
1. disable "django.middleware.csrf.CsrfViewMiddleware"
2. in new_trip page I have a button (Postdata)so this button sends an ajax request.
My View:-
#login_required
def save_journey(request):
if request.is_ajax() and request.method == "POST":
try:
res = json.loads(request.body)
cords = res['cords']
cords = [[x['d'], x['e']] for x in cords]
distance = res['distance']
start_place = res['start']
end_place = res['end']
clusters = clusterize_latlngs(cords, distance)
time = datetime.datetime.strptime(res['time'], "%m/%d/%Y %H:%M")
Trip.objects.create(user=request.user, time=time, cluster=json.dumps(clusters), travel_distance=distance,
start_place=start_place, end_place=end_place)
return HttpResponse()
except:
return HttpResponseBadRequest()
else:
return HttpResponseNotAllowed(['POST'])
Ajax call (home.js)
function postData() {
radius = 0;
var url = "/save_journey/";
var dataType = 'json';
if (type == 'r') {
radius = $('#radius').val();
url = "/get_results/";
dataType = 'html';
}
var data = JSON.stringify({
cords: myroute,
time: document.getElementById('dateStart').value,
start: document.getElementById('startPlace').innerHTML,
end: document.getElementById('endPlace').innerHTML,
radius: radius,
distance: distance
});
$.ajax({
type: "POST",
url: url,
dataType: dataType,
data: data,
success: function (data) {
if (type == 'r') {
window.location.href = "/search_results/";
}
else {
window.location.href = '/trip_success/';
}
},
error: function () {
console.log('Error getting options list...')
}
});
console.log(data);
}
this code is not able to call /save_journey/ URL.
I tried many answers from stack overflow & didn't figure out what is the problem .
You should never disable csrftoken unless you're absolutely sure about what you're doing. It's an important part of the security features implemented in Django.
Here is an example of how you can use Ajax with Django with csrftoken:
You can use Ajax Post to send JSON to Django and then handle the arguments as a dict(). Here is an example:
In browser (JQuery/JavaScript):
function newModule() {
var my_data = $("#my_element").val(); // Whatever value you want to be sent.
$.ajax({
url: "{% url 'modules' %}", // Handler as defined in Django URLs.
type: "POST", // Method.
dataType: "json", // Format as JSON (Default).
data: {
path: my_data, // Dictionary key (JSON).
csrfmiddlewaretoken:
'{{ csrf_token }}' // Unique key.
},
success: function (json) {
// On success do this.
},
error: function (xhr, errmsg, err) {
// On failure do this.
}
});
In server engine (Python):
def handle(request):
# Post request containing the key.
if request.method == 'POST' and 'my_data' in request.POST.keys():
# Retrieving the value.
my_data = request.POST['my_data']
# ...
Hope this helps.

Categories