20

I am trying to POST data using jQuery/AJAX in Django and am having trouble. When I run the code below and click on the 'test' button, the entire page re-loads again, which isn't what I want to happen (that's why I'm using AJAX).

I'm also not able to confirm the AJAX request is getting to the Django view.

EDIT: I've made the edits for return false and event.preventDefault(). A new page doesn't load, but I'm still not able to see the updated text in the <div id='message'> field. I'm not sure if the data is getting sent. I'm seeing in the console:

POST /edit_favorites/ HTTP/1.1" 403 2294

views.py:

from django.shortcuts import render_to_response
from django.http import HttpResponse

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

urls.py:

url(r'^edit_favorites/', 'edit_favorites'),

HTML:

<form method='post' id='test'>
  <input type="hidden" value="video34"/>
  <input type='submit' value='Test button'/>
  <div id='message'>Initial text</div>
</form>

JavaScript:

$(document).ready(function () {
  $("#test").submit(function (event) {
    event.preventDefault();
    $.ajax({
      type: "POST",
      url: "/edit_favorites/",
      data: {
        'video': $('#test').val() // from form
      },
      success: function () {
        $('#message').html("<h2>Contact Form Submitted!</h2>")
      }
    });
    return false;
  });
});

Any advice?

1
  • Breakpoint in the view; is the view code running? Breakpoint in the ajax success handler; is it running? Add ajax error handler; put breakpoint there; is it running? Also, 2 random side notes: you can use $('#test').serializeArray(), and it is recommended you capture only the url you mean to: url(r'^edit_favorites/$', ... (without the $ you capture any url beginning with that).
    – dokkaebi
    Commented Nov 20, 2012 at 2:44

3 Answers 3

16

Misplaced return false;. It should be at the end of .submit() function. So move it one line upwards:

$(document).ready(function () {
  $("#test").submit(function (event) {
    $.ajax({
      type: "POST",
      url: "/edit_favorites/",
      data: {
        'video': $('#test').val() // from form
      },
      success: function () {
        $('#message').html("<h2>Contact Form Submitted!</h2>")
      }
    });
    return false; //<---- move it here
  });

});

UPDATE:

About the issue POST /edit_favorites/ HTTP/1.1" 403 2294. Check on this post which looks similar to your issue:

5
  • I've made the edits for return false and event.preventDefault(). A new page doesn't load, but I'm still not able to see the updated text in the div id = 'message' field. I'm not sure if the data is getting sent.
    – sharataka
    Commented Nov 20, 2012 at 2:36
  • @sharataka Check this out, stackoverflow.com/questions/12744159/django-jquery-post-request Commented Nov 20, 2012 at 2:43
  • I believe it is because that's what I have in the urlconf.
    – sharataka
    Commented Nov 20, 2012 at 2:44
  • 4
    Looks like, you need to include a CSRF (cross-site request forgery) token in your ajax call. Commented Nov 20, 2012 at 2:46
  • @MuthuKumaran - I understand that it is possible to send ajax POST request to a different view than the one used to render the form initially. To that end, I have tried function view to post form data (serialized) but somehow the data is not posted to the DB. I can see the form data serialized in the console but unable to POST it to the DB. Is it possible for you to point to a minimal example of just doing what I am trying to acheive?
    – Stop War
    Commented Jul 7, 2020 at 4:56
6

the following methods worked to me. and i hope help you too.

from django.views.decorators.csrf import csrf_exempt
from django.http import HttpResponse

@csrf_exempt
def edit_favorites(request):
    if request.is_ajax():
        message = "Yes, AJAX!"
    else:
        message = "Not Ajax"
    return HttpResponse(message)
1
  • Are there any requirements for JsonResponse isted of HttpResponse Commented Sep 13, 2021 at 14:16
4

What is going on here is when you submit an HTML form, it sends the form's data to the action attribute of the <form>. In your javascript you subscribe to the submit event of the form, however you never disable the default behavior of the form, which is to follow the action attribute. In jQuery, you can modify that behavior by calling preventDefault method on the event argument, and returning false (if you call preventDefault, then returning false is not necessary but its better to make sure...):

$(...).submit(function(e) {
    e.preventDefault();
    ...
    return false;
});

EDIT

As for the error, your error is not very helpful but I have a hunch that you do not validate CSRF. More and detailed explanation of that here. Quick fix however is just to include this file in addition to your jQuery and add ensure_csrf_cookie decorator to your view.

4
  • I've made the edits for return false and event.preventDefault(). A new page doesn't load, but I'm still not able to see the updated text in the div id = 'message' field. I'm not sure if the data is getting sent.
    – sharataka
    Commented Nov 20, 2012 at 2:36
  • Does the text update to <h2>Contact Form Submitted!</h2>? In firebug do you get any errors?
    – miki725
    Commented Nov 20, 2012 at 2:39
  • I'm not using firebug, but I see "POST /edit_favorites/ HTTP/1.1" 403 2294 in the console...does this help troubleshoot?
    – sharataka
    Commented Nov 20, 2012 at 2:41
  • Not really but I have a hunch about CSRF. Check the edit in the answer.
    – miki725
    Commented Nov 20, 2012 at 2:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.