2

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 request is sent (example www.website.com/page/ will stay the same even with an ajax request). Basically, when I try to submit the ajax request I get a 403 error from the server. I believe part of my problem could be the url mapping in urls.py...

This is my ajax request:

$.ajax({
   type : "POST",
   url : "/page/update/",
   data : {
        data : somedata,
    },
}).done(function(data){
        alert(data);
});

This is the view it should get:

def update(request):
    if request.is_ajax():
        message = "Yes, AJAX!"
    else:
        message = "Not Ajax"

    return HttpResponse(message)

This is my urls.py

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

Thank you in advance for the help.

I looked a little more deeper into the error and the error states that I need to include {% csrf_token %} when sending a post back. This example how to get POST data in django 1.3 shows that its placed into a form however my request is only called on an on click function

Community
  • 1
  • 1
user1186173
  • 565
  • 3
  • 7
  • 26

1 Answers1

2

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 you
def update(request):
    if request.is_ajax():
        message = "Yes, AJAX!"
    else:
        message = "Not Ajax"

    return HttpResponse(message)

This is urls.py

urlpatterns = patterns('',
    url(r'^$', views.index, name='index'),
    url(r'^update/$', views.update, name='update'),
)
psorab
  • 135
  • 1
  • 16