csrf error while trying to delete an object with ajax - django

I have all the objects from my db rendered on my template by an ajax function.
Near every object there's a button that should delete it from the db but since I'm working on Django it raise a csrf_token missing or incorrect error.
I'm not using a form so I don't know how to include the csrf_token.
var $orders = $('#orders')
$.ajax({
type: 'GET',
url: 'http://127.0.0.1:8000/MyApp/list-api/?format=json',
success: function(orders) {
$.each(orders, function(i, order){
$orders.append('<li>name: '+order.name+', drink:
'+order.drink+'</li>')
$orders.append("<button data-id=" +(order.pk)+"
class='remove'>X</button>")
});
},
error: function() {
alert('errore caricamento ordini');
}
});
$orders.delegate('.remove', 'click', function(){
$.ajax({
type: 'DELETE',
url: 'http://127.0.0.1:8000/MyApp/list-api/' +
$(this).attr('data-id')
});
});
When I press a remove button a new request appears in the network panel of the browser, the response states :detail: "CSRF Failed: CSRF token missing or incorrect." The console gives a 403 forbidden error.
Any help or hints are really appreciated.

Related

CSRF token missing - django/ajax

CSRF token missing - django/ajax
Have already tried each and every solution proposed in this article but nothing seems to work for me.
"CSRF token missing or incorrect" while post parameter via AJAX in Django
$(document).on('click', '.attendance_submit', function(){
var urlname = '{% url "test" %}'
var tableSel = $('.attendance_table tr:not(.group)');
alert("DATA :"+html2json(tableSel));
$.ajax({
url : urlname,
type: 'POST',
dataType: 'json',
contentType: 'application/json',
data: {
csrfmiddlewaretoken: '{% csrf_token %}',
'TableData': html2json(tableSel)
},
success:
alert('Attendance updated successfully')
});
return false;
});
PS:
CSRF Token is also enabled in the form which I am using in this template, even tried removing from the form but to no avail.
I was finally able to solve this problem using the below code
#SeriForte 's answer pointed me in the right way when I was trying to troubleshoot some other issue.
{ "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" }
$(document).on('click', '.attendance_submit', function(){
var urlname = $(this).attr('data-url');
var tableSel = $('.attendance_table tr:not(.group)');
const csrftoken =
document.querySelector('[name=csrfmiddlewaretoken]').value;
alert("DATA :"+html2json(tableSel));
$.ajax({
url : urlname,
method: 'POST',
headers:{
contentType: 'application/json',
'X-CSRFToken': csrftoken
},
body: JSON.stringify(html2json(tableSel)),
success:
alert('Attendance updated successfully')
});
return false;
});

Django - 403 (Forbidden): CSRF token missing or incorrect with Ajax call. Tried everything

I know this is a well worn question and I scoured the web and this website finding countless answers that boil down to the very same solutions and none of them worked for me and I do not know why. my info/trials so far:
suprisingly the csrf_exempt decorator does not work
tried setting up Headers/beforeSend once before all Ajax calls, it does not work (I tried setting the headers both in call and just once for all the ajax calls)
I can pick up the django token easily both via javascript or via django {{ token }}
django.middleware.csrf.CsrfViewMiddleware is present in the settings.py
python 3.8; django 2.2
[UPDATE] I tried removing contentType to no avail as well
here below you can see the different trials in /*...*/
var csrftoken = '{{ csrf_token }}'
$.ajaxSetup({
crossDomain: false,
beforeSend: function(xhr, settings) {
xhr.setRequestHeader("X-CSRFToken", csrftoken)
}
});
$.ajax({
url: '/do_things/',
type: 'POST',
contentType: 'application/json',
data: {
/*'csrfmiddlewaretoken': csrftoken*/
},
beforeSend: function (xhr) {
/*xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');*/
/*xhr.setRequestHeader('X-CSRFToken', csrftoken);*/
/*xhr.setRequestHeader('X-CSRF-Token', csrftoken);*/
},
headers: {
/*'X-CSRFToken': csrftoken,*/
/*'X-CSRF-Token': csrftoken*/
},
success: function (data) {
console.log('Fill all the tables')
}
})
on the view side
#login_required(login_url='/login/')
def do_things(request):
if request.method == "POST":
...
on the url side ( in case I messed up something here):
urlpatterns = [
#...
path('r/', views.do_things, name='do_things'),
]
Resources:
a) Forbidden (CSRF token missing or incorrect.) | Django and AJAX
b) Adding CSRFToken to Ajax request
c) https://docs.djangoproject.com/en/2.2/ref/csrf/
let csrftoken = '{{ csrf_token }}'
$.ajax({
type: "POST",
headers:{'X-CSRFToken':csrftoken},
url: "{% url 'Wishlist' %}",
data: {'product_id':product_id},
success: function (response) {
console.log(response, typeof(response))
}
})
I used simple ajax with csrf in the header and it's working fine.
when i use your code in mine, so function calls but data gets blank. i have refered this Django csrf token for Ajax

flask endpoint for ajax call

I'm making an ajax call to my server while pressing submit button.
Button is present in page http://127.0.0.1:5000/post/15.
Jquery function invoked and the endpoint definition for submit_comment in python respectively:
function submit_comment(post_id) {
var uname = $('input[name="uname"]').val();
var comment = $('textarea[name="comment"]').val();
$.ajax({
url: "/submit_comment",
data: {name: uname, comment: comment, post_id: post_id},
method: "POST",
datatype: 'json',
success: function(response) {
console.log('reaches here');
addElement(response);
console.log('Is it me');
},
error: function(error) {
console.log('reached Error');
console.log(error);
}
});
}
py
#main.route('/submit_comment', methods = ['POST', 'PUT'])
def submit_comment():
entry = request.get_json(force=True)
print 'comment:', entry
....
Main is the blueprint. But I'm getting following 404 error.
127.0.0.1 - - [24/Aug/2017 10:30:55] "POST /post/submit_comment HTTP/1.1" 404 -
I am wondering from where this post got appended into the endpoint.
Can someone help me to understand the error and resolve it?
Thanks,
Deepak
I don't know a lot, but I know that the Flask docs on ajax say to query for the script root like this:
$SCRIPT_ROOT = {{ request.script_root|tojson }};
and then use that as part of the request URL.
An example from an ajax call I've used ($.getJSON being a jquery function for $.ajax)
$.getJSON($SCRIPT_ROOT + '{{ url_for("help_email") }}',

Forbidden (CSRF token missing or incorrect.):

I am making ajax call like below:
var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken': '{{ csrf_token }}'};
$.ajax({
type: 'POST',
url:"/issuebook",
data:data_dict,
processData: false,
contentType: false,
success:function(response)
{
}
});
urls.py is:
urlpatterns = [
url(r'^$',views.checkLogin,name='checklogin'),
url(r'^mylibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.MyLibrary.as_view()),name='mylibrary'),
url(r'^centrallibrary/(?P<pk>\d+)/(?P<user_name>[\w\-]+)$',login_required(views.CentralLibrary.as_view()),name='centrallibrary'),
url(r'^issuebook$',login_required(views.IssueBookView.as_view()),name='issuebook'),
]
I am getting "Forbidden (CSRF token missing or incorrect.): /issuebook" error on ajax call.
The csrf token in ajax call is getting rendered as:
var data_dict = {'user':{{ user.id }}, 'bookId':that.id, 'csrfmiddlewaretoken':'fSSdu8dJ4FO6FvDz8eU5ISzOewRYyGbC'};
$.ajax({
type: 'POST',
url:"/issuebook",
data:data_dict,
contentType: false,
success:function(response)
{
}
});
This error is caused by processData and contentType options in your ajax function. Removing these two options will fix the issue.
Explanation:
The arguments must be sent to Django as urlencoded with Content-Type application/x-www-form-urlencoded. Whereas, if you set processData: false it won't encode the POST parmaters and contentType: false will send ajax POST request as text/plain.

Create Item by using Item web api

I want to know how implement javascript method to create new item by using sitecore item web api.I am trying for below code my self.
But in the browser console show this error:
XMLHttpRequest cannot load http://myproject/-/item/v1/sitecore/Content/Home?name=MyItem5&template=Sample/Sample%20Item&sc_database=master. Request header field X-Scitemwebapi-Password is not allowed by Access-Control-Allow-Headers.
Please can anyone help me!!!!!!!
function createItem(){
jQuery.ajax({
crossDomain: 'true',
type: 'POST',
url: 'http://myproject/-/item/v1/sitecore/Content/Home?name=MyItem5&template=Sample/Sample Item&sc_database=master',
dataType: 'JSON',
contentType: 'application/x-www-form-urlencoded',
headers:{
"X-Scitemwebapi-Username":"sitecore\\Admin",
"X-Scitemwebapi-Password":"b",
},
success: function(data) {
alert(JSON.stringify(data));
},
error: function(res, error){
alert(JSON.stringify(res))
alert(res+ ' something is wrong');
}
});
}
Make sure you have these settings in your Sitecore.ItemWebApi.config
itemwebapi.mode="StandardSecurity"
itemwebapi.allowanonymousaccess="false"/>