7

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?

6
  • aare you sending the response as JSON from the server ?? or is it just HTML Commented Jun 26, 2013 at 6:40
  • What kind of the data are you sending back? JSON ("error" : true is not valid JSON)? If so, are you setting proper Content-Type response headers? Otherwise jQuery won't know that it is JSON and won't parse it automatically. Then you have to set the dataType: 'json' option. Commented Jun 26, 2013 at 6:41
  • sending response as JSON Commented Jun 26, 2013 at 6:42
  • Ok, so assuming that you are actually sending {"error": true}, add dataType: 'json' to the Ajax call options. Commented Jun 26, 2013 at 6:44
  • please look into the question again, I added server side code Commented Jun 26, 2013 at 6:47

4 Answers 4

8

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;
        });
    });
Sign up to request clarification or add additional context in comments.

1 Comment

Is responseText always defined?
1

You may use this code.. if you want to handle the error in web request ...

http://api.jquery.com/jQuery.ajax/

$.ajax({

}).done(function (data) {

}).fail(function (jqXHR, textStatus) {

});

And about in your server side validation you could return the error using json...

2 Comments

What do you put inside $.ajax({ } ?
@CyrilDuchon-Doris the data you are sending to the AJAX page. So in the OP's example, this would be data attribute i.e. $(this).serialize()
1

you have to use

error: function( jqXHR jqXHR, String textStatus, String errorThrown){
   ...
   ...
}

full documentation

Comments

0
  success: function(data)
  {
    if(data.error){
       //alert error
    }
    else{
       //alert('Success');
    }
  },
  error: function(XMLHttpRequest, textStatus, errorThrown)
  {
     alert('Internal server error');
     //some stuff on failure
  }

This error callback also handles the error, which are not caught at the server side.

2 Comments

Hey, if I put the mimetype or content_type in server its not working
I don't get it. Can you elaborate? What I mean is that if any uncaught exception comes on server side, then error callback will be called, not success.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.