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>
edit
on server side its 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 server side guy and seldom have to write JS. I sent "error" : true if there is an error with error message and "error" : false if no error on server!
I don't know why in the above code the conditional logic is not working!! Can anyone help me fix it?
This method is called when an HTTP request is successful. This method is called when an HTTP request fails. This method is called always, be the HTTP request fails or is successful. Example: We are going to see how to use AJAX fail() methods to handle the error in the HTTP requests.
When there is an AJAX error response or the AJAX request times out, you'll want to log as much information as you have, including the error message that jQuery gives you, the url and the request data. $. ajax(url, { "data": requestData, "type": "POST", "timeout": 5000 }) .
The ajaxError() method in jQuery is used to specify function to be run when an AJAX request fails. Syntax: $(document).ajaxError( function(event, xhr, options, exc) ) Parameter:: This method accepts single parameter function which is mandatory.
You'll need to stop it BEFORE the success handler. Because the function finishes executing after your AJAX call the form will submit while your ajax call is occurring (and by the time your ajax call finishes it is too late). But yes, put return false at the end of your function.
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;
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With