[Answer]-Django – posting comments using Ajax

1👍

You can’t redirect from an Ajax post. In fact, the whole point of doing Ajax at all is to prevent the need for redirecting. You need to actually return some data: the usual way to do that is to return some JSON indicating what happens. If the form was valid and the save succeeded, you might just return an empty response: but if the form was not valid, you’ll need to serialize the errors and return that as a JSON dict.

Then, in your Ajax script itself, you’ll need to process that information and display it to the user. Your Ajax function should look something like:

var form = $(this);
$.post(form.attr('action'), form.serialize())
   .done(function(data) {
       // do something on success: perhaps show a "comment posted!" message.
   })
   .fail(function(xhr, status, error) {
      // do something on failure: perhaps iterate through xhr.responseJSON and
      // and insert the error messages into the form divs.
   });

Leave a comment