Albita Vadillo
Albita Vadillo

Reputation: 11

403 error when making an ajax call through jQuery

This is a Django project, and I have to programme an online shop. In my html I have the form with the id "search", and I use this 'id' in my ajax code to search and compare with the date base I created.Finally it must show on the screen the possible data which are in my date base like a google finder.My big problem is with the CSRF,in the console I have: "POST /search/ HTTP/1.1" 403 2295 I read about people having the same problem on this page but I don't know where the fail is.

This my ajax code:

$("#search").keyup(function(){

    var cadena = $("#search").val();
    var csrf = $("input[name=csrfmiddlewaretoken]").val();
    var token = $('input[name=""__RequestVerificationToken""]').val();
    if ( cadena.length > 2){
        alert(cadena);

        $.ajax({
            type:"POST",
            url: "http://127.0.0.1:8000/search/",
            data:{'search_text':cadena,
                ''csrfmiddlewaretoken' : csrf},
            success:function(respuesta){
                $('#search-results').html(respuesta);
            }

        });
    }   
});

});

My template(html):

        <td>
            {% csrf_token %}
            <input type="text" id="search" placeholder="Search"/>
            <ul id ="search-results"></ul>
        </td>

My views.py:

def search_title(request):

if request.method == "POST":
    search_text = request.POST['search_text']
    libros1 = Libros.objects.filter(nombre__contains=search_text)
    print("asda");
else:
    search_text =''
    libros1 = Libros.objects.filter(nombre__contains=search_text)

return render('ajax_search.html',{'libros':libros1})

my url:

 url(r'^admin/',include(admin.site.urls)),
 url(r'^$', 'views.home'),
 url(r'^(search)/', 'views.search_title'),
 url(r'^(libros)/', 'views.libros'),
 url(r'^(carrito)/', 'views.carrito')

In the console I've got:

warnings.warn("A {% csrf_token %} was used in a template, but the context did not provide the value. This is usually caused by not using RequestContext.")

Upvotes: 0

Views: 642

Answers (2)

deep
deep

Reputation: 11

Luca's answer should solve your problem. I'd like to share how I normally implement AJAX POST requests. I write the jQuery code inside the template(html) file.

I know this isn't the best practice but doing so allows me to

  • Use the {% url %} tag instead of hard coding the url in the js file.

  • Use {{ csrf_token }} instead of fetching the value from the hidden input field.

Normally, I have a block called extrajs in my base.html file (the one which I extend on every single template) .

Now whenever i need to include AJAX functionality this is how i do it

{% block extrajs %}
<script>
...
$.ajax({
...
url:'{% url "app_name.views.func_name" %}',
data:{ ... ,'csrfmiddlewaretoken':'{{ csrf_token }}', ... },
...
});

</script>
{% endblock %}

Upvotes: 1

Luca
Luca

Reputation: 322

My suggestion is that you should make sure the csrf token keyword is inline with the middleware handling it (in your ajax it's csrtoken). In my django app, the token is called csrfmiddlewaretoken.

The ajax post request should look like the following:

        $.ajax({
        type:"POST",
        url: "http://127.0.0.1:8000/search/",
        data:{'search_text':cadena,
            'csrfmiddlewaretoken' : csrf},
        success:function(respuesta){
            $('#search-results').html(respuesta);
        }

Upvotes: 0

Related Questions