Skip to content Skip to sidebar Skip to footer

Sending Ajax Request To Django

I'm pretty new to Ajax and Django and I'm trying to send a simple ajax request to a function called 'update'. But I also don't want the actual url to change in the browser when the

Solution 1:

Your url in ajax request "/page/update/" doesn't match from urls.py.That is why you are getting 404 error page. I will show you my line code you can try this.

 $.ajax({
    type: "POST",
    url: "/update/"
    data: {
        csrfmiddlewaretoken: '{{ csrf_token }}',
        data : somedata,
    },
    success: function(data) {
        alert(data);
    },
    error: function(xhr, textStatus, errorThrown) {
        alert("Please report this error: "+errorThrown+xhr.status+xhr.responseText);
    }
});

/*'{{ csrf_token }}' is specifically for django*/

This is the views:

from django.views.decorators.csrf import csrf_exempt
@csrf_exempt //You can use or not use choice is left to youdef update(request):
    if request.is_ajax():
        message ="Yes, AJAX!"else:
        message = "Not Ajax"returnHttpResponse(message)

This is urls.py

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^update/$', views.update, name='update'),
)

Post a Comment for "Sending Ajax Request To Django"