1

I am doing an AJAX form post in jQuery. However, when I return an error code from my Python server,it's being read as success instead of as error. My code is below. I am a noob in Python. So apologize if I am making obvious mistakes.

Jquery:

 $.ajax({

                type:"post",
                url: "/newform",
                data:$('#my-form').serialize(),
                success: function(msg){

                    alert(msg);


                },
                error: function(msg){

                     alert(msg);
                }
            });

Python code:

def post(self):

    email = self.get_secure_cookie("user")
    id_name = self.get_argument('id1', None)

    try:
        credentials = Credentials(email=email, id_name=id_name)
        credentials.save()

    except Exception, e:
        print '%s' % str(e)
        msg = 'Authorization Failed. Please check if the credentials are correct'
        status = "error"

    else:
        msg = 'Connected'
        status = "success"

    print 'status: %s' % status
    self.write({"status": status, "msg": msg})
3
  • "success" only means that the server responded with an HTTP Status code of 200. Your JavaScript has no idea if an error happened on the server side. Commented Oct 13, 2014 at 12:47
  • Yes, was making a noob mistake. Thanks for explaining. Commented Oct 13, 2014 at 13:16
  • No worries. Glad you figured it out. Commented Oct 13, 2014 at 13:17

2 Answers 2

3

Your code is still returning a successful HTTP 200 response, but with "status":"error" in it.

So your javascript could look like this:

$.ajax({
            type:"post",
            url: "/newform",
            data:$('#my-form').serialize(),
            success: function(msg){
                if (msg.status == "success") {
                //handle success here
                } else {
                //handle error
                }
            },
            error: function(msg){
            //handle server error, such as HTTP 404, 500
            }
        });
Sign up to request clarification or add additional context in comments.

Comments

1

On a technical level there are no erros. On a functional level there is an error. So the ajax call is done without errors. You have to check in the success handler the status field you are providing for error or success.

Comments

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.