Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

403 Forbidden error when making an ajax Post request in Django framework

I am trying to integrate jquery into a web application I am making with Django framework. I am however having a hard time trying to make a simple ajax call to work. My template file that contains the form html and javascript to handle the ajax call looks like:

<script type="text/javascript"> $(document).ready(function() { $( "#target" ).submit(function() { console.log('Form was submitted'); $.ajax({         type: "POST",         url: "/hello/",  // or just url: "/my-url/path/"         data: {             query: $( "#query" ).val()            },         success: function(data) {             console.log(data);         }     }); return false;   });      }) </script> <form id="target" action="." method="post">{% csrf_token %}  <input id= "query" type="text" value="Hello there">  <input type="submit" value="Search Recent Tweets"> </form> 

My views.py that is supposed to handle the ajax call looks like:

 from django.core.context_processors import csrf  from django.shortcuts import render_to_response  from django.template.loader import get_template  from django.template import Context,RequestContext  from django.views.decorators.csrf import ensure_csrf_cookie  from django.http import HttpResponse   # access resource  def hello(request):   c = {}   c.update(csrf(request))   if request.is_ajax():         t = get_template('template.html')         #html = t.render(Context({'result': 'hello world'}))         con = RequestContext(request, {'result': 'hello world'})         return render_to_response('template.html', c, con)   else:         return HttpResponse('Not working!')  

I have tried to follow the official documentation on Cross-Site Request Forgery Protection and also looked at several stackoverflow questions addressing a similar problem. I have included the {% csrf_token %} in my html template file but it still doesn't seem to be working. I get an error in the console suggesting that the ajax call failed:

POST http://127.0.0.1:8000/hello/ 403 (FORBIDDEN)    

How do I pass the result variable along with my http response and get the ajax call to work smoothly? Any help is deeply appreciated.

Edit-1

I wasn't supposedly passing the csrf token along with my post request. SO as per the documentation I added the following code to my template javascript:

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'); console.log(csrftoken);  //Ajax call function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({     crossDomain: false, // obviates need for sameOrigin test     beforeSend: function(xhr, settings) {         if (!csrfSafeMethod(settings.type)) {             xhr.setRequestHeader("X-CSRFToken", csrftoken);         }     } }); 

When I refresh the template html page in the browser, I get null in the console, suggesting that the cookie is not set or not defined. What am I missing?

like image 723
Annihilator8080 Avatar asked Oct 12 '13 10:10

Annihilator8080


People also ask

What does Ajax error 403 mean?

The reason of 403 error is you are not sending headers. Since you are making a CORS request, you cannot send any custom headers unless server enables these header by adding Access-Control-Allow-Headers to the response. In a preflighted-request, client makes 2 requests to the server.

Does AJAX work with Django?

Using Ajax in Django can be done by directly using an Ajax library like JQuery or others. Let's say you want to use JQuery, then you need to download and serve the library on your server through Apache or others. Then use it in your template, just like you might do while developing any Ajax-based application.


1 Answers

Because you did not post the csrfmiddlewaretoken, so Django forbid you. this document can help you.

like image 65
Yohn Avatar answered Sep 20 '22 01:09

Yohn