4

in template:

<script type="text/javascript">
        $.ajax({
             type:"POST",
             url:"{% url DrHub.views.ajxTest %}",
             data: {
                    'start': $('#id_startTime').val(),
                    'end': $('#id_endTime').val(),
                    'csrfmiddlewaretoken': '{{ csrf_token }}'
             },
             success: function(data){
                 alert(data);
             }
        });
</script>
.
.
.
<form method='POST' action=".">
    {% csrf_token %}
    <input type="text id="id_startTime" />
    <input type="text id="id_endTime" />
    <input type="submit" value="send" />
</form>

in views:

def ajxTest(request):
   if request.is_ajax():
      if request.method == 'POST':
         return HttpResponse(json.dumps({'message' : 'awesome'},ensure_ascii=False), mimetype='application/javascript')

in settings.py:

MIDDLEWARE_CLASSES = (
    'django.middleware.common.CommonMiddleware',
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.locale.LocaleMiddleware',
)

when submitting form I have this error:CSRF verification failed. Request aborted.

I searched alot but none of suggested solutions worked for me!

like : Django CSRF check failing with an Ajax POST request

and : Ajax Post in Django framework?

I refreenced to a js file with this content:

$.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'));
         }
     } 
});

but this didn't work,too!

And I saw a solution that say use ajaxSetup instead of ajaxSend to post data,how can I do this?

Community
  • 1
  • 1
Asma Gheisari
  • 5,794
  • 9
  • 30
  • 51
  • 1
    have you checked in the firebug that the CSRF token value are being posted – Rafay Feb 21 '12 at 18:44
  • I don't know how to use firebug :D – Asma Gheisari Feb 21 '12 at 18:45
  • 2
    you can get it from here http://getfirebug.com/ its a firefox extension – Rafay Feb 21 '12 at 18:47
  • I installed firebug but I didn't understand it! – Asma Gheisari Feb 21 '12 at 19:18
  • when your page is loaded press f12 a window will popup infront of you, now inside that window go to `Net` tab and inside that tab select `XHR`, now do the ajax request it will be shown there – Rafay Feb 21 '12 at 19:28
  • In your browser, do a "view source" on your page and verify that the csrftoken value has been inserted into your javascript. – Brian Neal Feb 21 '12 at 20:26
  • @3nigma when I go to Net tab I don't find XHR !! – Asma Gheisari Feb 23 '12 at 05:34
  • @Asma you must be doing something wrong... – Rafay Feb 23 '12 at 06:01
  • @Asma see here http://i.imgur.com/reo3R.png – Rafay Feb 23 '12 at 06:17
  • @3nigma I tryed this in a simple form then I checked firebug and I got error "403 forbidden" in jquery.js file in this part: // Send the data try { xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null ); } catch(e) { jQuery.handleError(s, xhr, null, e); // Fire the complete handlers complete(); } in line XHR.send... – Asma Gheisari Feb 23 '12 at 06:24
  • can you check what parameters were sent in the request, check the params tab when you click on the error message – Rafay Feb 23 '12 at 06:32
  • I don't have params tab!!!! but at Post tab I can see my parameters just when I give fixed value to theme,like: start: "8", end: "12", csrfmiddlewaretoken:"SDSDSFSF" – Asma Gheisari Feb 23 '12 at 06:51

8 Answers8

5

You should pull the csrfmiddlewaretoken from the dom element:

{'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()}

The above is exactly what I do in several places and it works.

Edit just to add some clarity drawing from your material:

<script type="text/javascript">
    $.ajax({
         type:"POST",
         url:"{% url DrHub.views.ajxTest %}",
         data: {
                'start': $('#id_startTime').val(),
                'end': $('#id_endTime').val(),
                'csrfmiddlewaretoken':$( "#csrfmiddlewaretoken" ).val()
         },
         success: function(data){
             alert(data);
         }
    });
</script>
Marcin
  • 48,559
  • 18
  • 128
  • 201
James R
  • 4,571
  • 3
  • 30
  • 45
4

having this a refrence to a js file with this content was my solution:

jQuery(document).ajaxSend(function(event, 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;
    }
    function sameOrigin(url) {
        // url could be relative or scheme relative or absolute
        var host = document.location.host; // host + port
        var protocol = document.location.protocol;
        var sr_origin = '//' + host;
        var origin = protocol + sr_origin;
        // Allow absolute or scheme relative URLs to same origin
        return (url == origin || url.slice(0, origin.length + 1) == origin + '/') ||
            (url == sr_origin || url.slice(0, sr_origin.length + 1) == sr_origin + '/') ||
            // or any other URL that isn't scheme relative or absolute i.e relative.
            !(/^(\/\/|http:|https:).*/.test(url));
    }
    function safeMethod(method) {
        return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method));
    }

    if (!safeMethod(settings.type) && sameOrigin(settings.url)) {
        xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
    }
});
Asma Gheisari
  • 5,794
  • 9
  • 30
  • 51
4

There's also another shortcut to this. I wouldn't know if the security thing here is of so much value and importance. I ran into this problem but there seems to be a lot of hacks around this that end up trying to submit the csrftoken from an existing cookie. I don't know what would happen if this cookie does not exist or was not set.

My approach was to add a @csrf_exempt to the view that processes the ajax post. You import the csrf_exempt from django.views.decorators.csrf

Like this:

from django.views.decorators.csrf import csrf_exempt

And than, from the view method:

@csrf_exempt
def the_method_to_be_called(request):

...

see this link

hagay
  • 85
  • 1
  • 9
Peter
  • 6,509
  • 4
  • 30
  • 34
1

in HTML(template)

{% csrf_token %}

in JS

$.ajax({
    type: "POST",
    url: '/brand-admin/publish_article/',
    data: {
      'article_id': article_id,
      'csrfmiddlewaretoken':$( "input[name='csrfmiddlewaretoken']" ).val()
    },
    dataType: 'json',
    success: function (data) {
      console.log(data);
    }
  });
Zhong Ri
  • 2,556
  • 1
  • 19
  • 23
1

I have solve it by doing following:

let data = {};
data.somedata = somedata;
data.csrfmiddlewaretoken = '{{ csrf_token }}';

  $.ajax({
          type: 'POST',
          url: "/myadmin/user/medical/"+rowId,
          data: data,
          dataType: "json",
          success: function(resultData) { alert("Save Complete") }
        });

Hope this will work for someone.

Rajesh Patel
  • 1,946
  • 16
  • 20
0

Please add the csrfmiddlewaretoken as csrfmiddlewaretoken: {% csrf_token %} in your js.

<script type="text/javascript">
        $.ajax({
             type:"POST",
             url:"{% url DrHub.views.ajxTest %}",
             data: {
                    'start': $('#id_startTime').val(),
                    'end': $('#id_endTime').val(),
                    'csrfmiddlewaretoken': '{% csrf_token %}'
             },
             success: function(data){
                 alert(data);
             }
        });
</script>
Sangram Shivankar
  • 3,535
  • 3
  • 26
  • 38
Harris
  • 1
0

If the {% csrf_token %} is in your form on your template:

<form id="the-form" autocomplete="off">
    {% csrf_token %}
    <input type="text" name="q">
    <input type="submit" value="Submit">
</form>

you should be able to send it up using:

$("#the-form").submit(function(e){
  e.preventDefault();
  $.ajax({
    type: "POST",
    url: "/post-url",
    data: $("#the-form").serialize(),
    success: function(data){
      console.log(data);
    }
  });
});
chaggy
  • 1,091
  • 1
  • 10
  • 18
0

SIMPLEST WAY: csrfmiddlewaretoken will be available in dom elements.

Just fetch the csrfmiddlewaretoken from the dom elements using the name as shown below:

'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()

You can fetch it by id also, but sometimes that dom element won't be carrieng id, So this is the best way.

You can just copy paste the following code:

    $.ajax({
        type:"POST",
        url:"{% url DrHub.views.ajxTest %}",
        data: {
                'start': $('#id_startTime').val(),
                'end': $('#id_endTime').val(),
                'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
        },
        success: function(data){
            alert(data);
        }
    });
Mohit Rathod
  • 1,057
  • 1
  • 19
  • 33