19

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?

daaawx
  • 3,273
  • 2
  • 17
  • 16
sharataka
  • 5,014
  • 20
  • 65
  • 125
  • 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 Nov 20 '12 at 02:44

3 Answers3

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:

daaawx
  • 3,273
  • 2
  • 17
  • 16
Muthu Kumaran
  • 17,682
  • 5
  • 47
  • 70
  • 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 Nov 20 '12 at 02:36
  • @sharataka Check this out, http://stackoverflow.com/questions/12744159/django-jquery-post-request – Muthu Kumaran Nov 20 '12 at 02:43
  • I believe it is because that's what I have in the urlconf. – sharataka Nov 20 '12 at 02:44
  • 4
    Looks like, you need to include a CSRF (cross-site request forgery) token in your ajax call. – Muthu Kumaran Nov 20 '12 at 02: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? – Love Putin Not War Jul 07 '20 at 04: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)
Zhengquan Feng
  • 171
  • 2
  • 3
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.

miki725
  • 27,207
  • 17
  • 105
  • 121
  • 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 Nov 20 '12 at 02:36
  • Does the text update to `

    Contact Form Submitted!

    `? In firebug do you get any errors?
    – miki725 Nov 20 '12 at 02: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 Nov 20 '12 at 02:41
  • Not really but I have a hunch about CSRF. Check the edit in the answer. – miki725 Nov 20 '12 at 02:44