I'm working on a site that keeps track of a to-do list and pulls it from a server. There are two sample ajax calls below. The tasks GET call works fine, however the add POST does not. For some reason, it gives me a 403 forbidden error and as a result, doesn't execute the code.
I was looking at 403 Forbidden error when making an ajax Post request in Django framework and i read the link posted by @yohn, but I'm not understanding how to implement this solution.
var tasker = (function() {
return {
tasks : function( ownerId, cb ) {
$.ajax({
url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c",
type: 'GET',
success: function(task) {
if(task){
var list = []
for(var a=0; a<task.length; a++){
var newTask = {
onwerId: task[a].ownderId,
desc: task[a].desc,
due: new Date(task[a].due),
color: task[a].color,
complete: task[a].complete,
id: task[a].id
};
list.push(newTask);
}
cb(list , null);
}
else{ cb(null, 'error retreiving your tasks');}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! " + errorThrown );
},
});
},
add : function( ownerId, task, cb ) {
$.ajax({
url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c",
type: 'POST',
success: function(task) {
var d = new Date(task.due);
if(task){
var newTask = {
onwerId: task.ownderId,
desc: task.desc,
due: d,
color: task.color,
complete: task.complete,
id: task.id
};
cb(newTask , null);
}
else{cb(null, 'error adding your task');}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! " + errorThrown );
},
});
},
}
})();
Django requires a csrf
token when making POST requests (unless you are using token based authentication but I am assuming you are not here). It's just like when you need to include {{ csrf_token }}
in form submit.
For more information about the why you need it and the purpose of csrf tokens: What is a CSRF token ? What is its importance and how does it work?
So for your problem, change your ajax call under add
to this:
$.ajax({
url: "http://138.49.184.143:3000/tasker/api/"+ownerId+"?key=f725ebbc9c",
type: 'POST',
data: { csrfmiddlewaretoken: '{{ csrf_token }}'}, // added csrf token.
success: function(task) {
var d = new Date(task.due);
if(task){
var newTask = {
onwerId: task.ownderId,
desc: task.desc,
due: d,
color: task.color,
complete: task.complete,
id: task.id
};
cb(newTask , null);
}
else{cb(null, 'error adding your task');}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem! " + errorThrown );
},
});
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.