0

I'm not sure why I get this error. I have favorite app, and ajax must be falling apart. because this error occurs when I click a button that should work but not working right now. my guess is I;m missing some csrf or cookie or wrong jquery version.... I'm not sure. This is my code

and in html file

<div class="actions">{% if user.is_authenticated %}{% fav_item category user %}{% endif %}</div>
</div>

I'll post views.py as well

def ajax_login_required(view_func):
    def wrap(request, *args, **kwargs):
        if request.user.is_authenticated():
            return view_func(request, *args, **kwargs)
        json = simplejson.dumps({'not_authenticated': True})
        return HttpResponse(json, content_type='application/json', status=401)
    wrap.__doc__ = view_func.__doc__
    wrap.__dict__ = view_func.__dict__
    return wrap

@ajax_login_required
def ajax_fav(request, ctype_id, obj_id):
    """

    """
    ctype = get_object_or_404(ContentType, pk=ctype_id)
    item = ctype.get_object_for_this_type(pk=obj_id)    
    if Favorite.objects.filter(user=request.user, content_type=ctype, object_id=obj_id):
        fav = Favorite.objects.get(user=request.user, content_type=ctype, object_id=obj_id)
        fav.delete()
        count = Favorite.objects.favorites_for_object(item).count()
        data_dict = {'id': 0, 'message': fav_settings.FAV_ADD, 'counter': build_message(count), }
    else:        
        fav = Favorite.objects.create_favorite(item, request.user)
        count = Favorite.objects.favorites_for_object(item).count()
        data_dict = {'id': fav.id, 'message': fav_settings.FAV_REMOVE, 'counter': build_message(count), }
    return HttpResponse(simplejson.dumps(data_dict), content_type='application/javascript')

Edit: /In Console I get js error Uncaught SyntaxError: Unexpected identifier

$(function(){
    $('a.favIt').on('click', function(){      
        var itemId = $(this).attr('id').split("_")[1];
        $.ajax({
            type: "POST",
            url: $(this).attr("href"),
            data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
            dataType: "json",
            timeout: 2000,
            cache: false,           
            beforeSend: function(XMLHttpRequest) {
                //$("#loader").fadeIn();
            },
            error: function(data, XMLHttpRequest, textStatus, errorThrown){
                $(this).html("Error connecting to the server.");
            },              
            complete: function(XMLHttpRequest, textStatus) {
                //$("#loader").fadeOut();
            },                        
            success: function(data, textStatus, XMLHttpRequest){
                $('#FavIt_'+itemId).html(data.message);
                $('#FavCounter_'+itemId).html(data.counter);
            }
            });             
        return false;
    });
});

it says its occuring from line 8 which is dataType: "json", I posted views.py

mike braa
  • 647
  • 1
  • 12
  • 33
  • It looks like the answers to this point may help: http://stackoverflow.com/questions/13035412/django-ajax-post-403-forbidden?rq=1 – Rob W. Jan 26 '16 at 15:00

1 Answers1

1

You need to pass the csrf token as part of the data in ajax call:

data: {csrfmiddlewaretoken: '{{ csrf_token }}'}
Shang Wang
  • 24,909
  • 20
  • 73
  • 94
  • "and in html file" kind of suggests that the ajax is in a separate js file.. but yes, missing csrf token for which there are plenty duplicates. – Sayse Jan 26 '16 at 14:59
  • 1
    @sayse: That's a good point. mike, you might read this answer as well: http://stackoverflow.com/questions/23349883/how-to-pass-csrf-token-to-javascript-file-in-django?answertab=votes#tab-top. – Shang Wang Jan 26 '16 at 15:02
  • Thank you S, S of course as Shane – mike braa Jan 26 '16 at 15:19
  • @ShangWang I get Uncaught SyntaxError: Unexpected identifier now that I changed,,,do you know why?? – mike braa Jan 26 '16 at 15:36
  • That's too little information for me to help you. In python you should always let people see the backtrace to check for the error. You should learn how to read the backtrace as well. Can you edit you question to reflect that? – Shang Wang Jan 26 '16 at 15:45
  • @ShangWang thanks for taking a look at this...I've been trying to get this thing to work for so long. Can you tell me which file is needed? I'm using django-favorites app from https://bitbucket.org/last_partizan/django-favorites....when I click add fav, it goes to http://127.0.0.1:8000/follow/fav/8/1/ where it should just be a button. the whole backend works i think since it's being marked as favorite and changed to unfavorited – mike braa Jan 26 '16 at 16:06
  • Again, you need to edit your original question to include the full backtrace of your python error. I can only check the error from that. – Shang Wang Jan 26 '16 at 16:21