[Django]-How do I POST with jQuery/Ajax in Django?

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:

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)

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.

Leave a comment