How to add error handling in a jQuery Ajax form view
This is my code.
<script type="text/javascript"> $(document).ready(function() { $('#spc-comment-flag-form').submit(function() { $.ajax({ data: $(this).serialize(), type: $(this).attr('method'), url: $(this).attr('action'), success: function(data) { if( data['error'] == false) { var msg = 'We got your flag. Our moderators will now look into it. You may close the window now!'; $('#spc-comment-flag-response').html(msg); } else { $('#spc-comment-flag-response').html(data); } }, }); return false; }); }); </script> change
on the server side this is something like this:
@csrf_protect @login_required def flag(request, comment_id, next=None): if not request.is_ajax(): raise Http404 data = {} if request.method == 'POST': ... data = simplejson.dumps(data) return HttpResponse(data, mimetype="application/javascript") else: raise Http404 I am basically a server side guy and rarely have to write JS. I sent "error": true if there is an error with an error message and "error": false if there is no error on the server!
I donβt know why in the above code the conditional logic does not work! Can someone help me fix this?
try this one ...
$(document).ready(function() { $('#spc-comment-flag-form').submit(function() { $.ajax({ data: $(this).serialize(), type: $(this).attr('method'), url: $(this).attr('action'), success: function(data) { if( data['error'] == false) { var msg = 'We got your flag. Our moderators will now look into it. You may close the window now!'; $('#spc-comment-flag-response').html(msg); } else { $('#spc-comment-flag-response').html(data); } }, error: function (data) { var r = jQuery.parseJSON(data.responseText); alert("Message: " + r.Message); alert("StackTrace: " + r.StackTrace); alert("ExceptionType: " + r.ExceptionType); } }); return false; }); }); You can use this code .. if you want to handle the error in the web request ...
http://api.jquery.com/jQuery.ajax/
$.ajax({ }).done(function (data) { }).fail(function (jqXHR, textStatus) { }); And in your server side check you can return an error using json ...