Reputation: 6304
I am trying to get ajax to work, but I keep getting a 403 error. I am quite new to jquery.
The following is my code
$('#prod_search_button').click(function(){
if ($('#inv_prod_list').length) {
//insert a new record
}
else
{
//create the #inv_prod_list table and insert first record
var inv_table= '<table id="inv_prod_list" style="border: 2px solid #dddddd;"></table>';
// create query object
var prod_query = {
query: jQuery.trim($('#id_prod_query').val())
};
// convert object to JSON data
var jsonQuery = JSON.stringify(prod_query);
$.ajax({
type: 'POST',
url: '/company/product/item_search.json/',
data: jsonQuery,
success: function(jsonData){
var parsed = JSON.parse(jsonData);
$('#inv_prod_wrap').html(inv_table);
var new_record = 'this is html for new row'
$('#inv_prod_list tr:last').after(new_record);
//off rows alt color
}
});
}
});
Upvotes: 9
Views: 15521
Reputation: 211
For request type POST
, just add a reference to csrf_token:
$.ajax({
type: 'POST',
url: ...,
data: ...,
'csrfmiddlewaretoken': '{{csrf_token}}', // Added csrf_token
success: function(jsonData){
// ...
},
});
Upvotes: 0
Reputation: 103
just copy that piece of code from the official docs into a js file and include it in your html
// using jQuery
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);
}
}
});
Upvotes: 2
Reputation: 5305
Can also check if csrf middleware is enabled in settings.py and disable it. Look for 'django.middleware.csrf.CsrfViewMiddleware'
.
Upvotes: 0
Reputation: 380
You can avoid the CSRF by adding the following annotation before your method definition.
from django.views.decorators.csrf import csrf_exempt
@csrf_exempt
def Method():
Upvotes: 3
Reputation: 5734
I ran into this and figured I'd post what was going on. I had the {% CSRF_TOKEN %}
in a cached paged and it was caching what it put there. So for some users it was valid and some it wasn't depending on the cache! It was a nightmare to track down even though it should have been obvious... So check your caching.
Upvotes: 0
Reputation: 668
See the HTTP/1.1 Status Code Definitions. "403" is the status code "Forbidden". This is an error being thrown on the server side of your $.ajax
request, not the client side (i.e. your code is making a request, but the response from the server is an error message).
The document indicates servers should respond with that error only in specific situations:
The server understood the request, but is refusing to fulfill it. Authorization will not help and the request SHOULD NOT be repeated. If the request method was not HEAD and the server wishes to make public why the request has not been fulfilled, it SHOULD describe the reason for the refusal in the entity. If the server does not wish to make this information available to the client, the status code 404 (Not Found) can be used instead.
Typically, an error of this sort means that whatever user you're logged in as does not have access to the URL you are requesting. Often, this indicates that the only error in your code is the URL you are making the request to or the ordering of a sequence of calls (e.g. you are trying to request data before logging in). Less commonly, some web servers and web applications are configured to respond with 403 error codes instead of 404 (not found) error codes for all "invalid" requests to avoid leaking information about what files do/don't exist on the server.
Upvotes: 0