5

I have the following ajax call to update a particular field of a model

$("#updateLink").click(function(){
    var dec_text = $('#desc_text').val();

    $.ajax({
        type: "POST",
        url:"/users/update_desc/",
        data: {
        'val': dec_text,
        },
        success: function(){
            $(".display, .edit").toggle();
            $("#descText").html(dec_text);
        },
        error: function(){
            alert("Error");
        },
    });
    return false;
});

and my view is this

@csrf_exempt
def update_desc(request):
    if request.is_ajax():
        if request.method == 'POST':
            desc_text = request.POST.get('val', False)
            if desc_text:
                profile = user.profile
                profile.desc = desc_text
                profile.save()

            return_message = "Sent mail"
            return HttpResponse(return_message,mimetype='application/javascript')

I am constantly getting an error message and I don't know how to solve this. I even used the csrf_exempt decorator to workaround if the problem was caused by a missing csrf token but still the problem persists.

Except one ajax post which in my base template all the ajax calls are failing. Can anybody please help to understand what is happening here. I can give some more details if required.

Edit:

I have added the a js file containing this https://docs.djangoproject.com/en/dev/ref/contrib/csrf/#ajax in my base template, so it means it is present in all my templates. And I am using django 1.3 version.

Sachin
  • 3,672
  • 9
  • 55
  • 96
  • I am expecting that you are still getting the csrf_token missing error. If so my answer is posted below else state the error after you are used csrf_exempt. – Zain Khan Dec 30 '11 at 07:55
  • Actually I do not know how to get the error, as you can see I have just put an alert in my `error` callback which tells me that my ajax call failed but it does not tell me what the error was. How can I get the error? – Sachin Dec 30 '11 at 07:59
  • Firstly, in your settings.py file DEBUG = True. This would not display your ajax errors but definitely others which are not catered. – Zain Khan Dec 30 '11 at 08:02
  • 1
    Secondly, download FireBug. That is a very useful tool for debugging. In there you would have a console panel. Click on it and reload your page. This would show any scripts that failed. Go on the line and copy error or open it in another tab. This would take you to the crash page if so – Zain Khan Dec 30 '11 at 08:03
  • Yes that I had already sent, before adding the solution that you have given below I was getting this `[30/Dec/2011 13:27:36] "POST /users/update_desc/ HTTP/1.1" 500 94752` Now I don't see a post call being made at all, so it means the below solution is not helping. Can you suggest something else. Why am I getting a 500, is something wrong with my `view`? – Sachin Dec 30 '11 at 08:04
  • Try using console.log('Successful') in the success function I wrote below in answer. If Successful is printed in the console of firebug then your view is working alright. Else you would have to debug your view. – Zain Khan Dec 30 '11 at 08:09
  • Thanks alot, I figured out why I was getting that error, there was some problem with my view. But is it necessary for me to use `csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value` because now it is working without that also – Sachin Dec 30 '11 at 08:11
  • Are you still using the POST method? It shouldn't work using POST without the CSRF middleware token. – jeffknupp Dec 30 '11 at 11:32
  • I am using the `POST` method, and I am not using the middleware however I have added the `ajaxSend` javascript that has been given in the documentation – Sachin Dec 30 '11 at 12:29

1 Answers1

6

Firstly, you are using POST and not sending a csrf token. Try explicitly sending the csrf token rather than using the decorator csrf_exempt.
One way of doing this is with what I have done in data. That is to fetch the csrf token (or from your own method) and pass it in your arguments.

$.ajax({
        url : url,
        type: "POST",
        data : {csrfmiddlewaretoken: document.getElementsByName('csrfmiddlewaretoken')[0].value},
        dataType : "json",
        success: function( data ){
            // do something
        }
    });
Zain Khan
  • 3,753
  • 3
  • 31
  • 54