1

I have a form in html, I'll do the validation on the server side. If the validation fails, the errorDiv will be updated, otherwise the resultDiv will be updated.

I have two options to handle this. My friend said the validation failure should handle in the on success part of ajax call. While I think put the logic in the error part might be better.

Some of his concerns might be:

  • The validation error is not some error like network connection failure which should use some status code like 400; or any server side error, which using the status code 500.

My concern is:

  • If we put the logic in the error part, the logic seems more clear;
  • we can use some other status code (although I don't know right now) rather than 400, 500 to indicate the validation error.

My friend's Option 1:

$.ajax({
    type:'POST',
    data:someFormData,     
    url:'/submitToServer',
    success:function(data,textStatus) {
        if(data.hasValidationError){
            $('#errorDiv').html(data);
        }else{
            $('#resultDiv').html(data);
        }
    }
});

My Option 2:

$.ajax({
    type:'POST',
    data:someFormData,     
    url:'/submitToServer',
    success:function(data,textStatus) {
        $('#resultDiv').html(data);
    },
    error:function(XMLHttpRequest,textStatus,errorThrown){
        if(textStatus==500)
             $('#errorDiv').html(errorThrown);
    }
});

I do know both ways can handle the validation errors, but which way is better? Which way are you using? Please give me some pros and cons...

Thank you guys so much!

1
  • Hmm this question is not really on topic here, its a person opinion thing, personally I would through an error from the server side. That way if you ever reuse the code its clear there is an error. Commented Feb 17, 2015 at 20:37

1 Answer 1

1

i have to agree with your friend. the error part is not designed for that use. the official document it clearly say:

A function to be called if the request fails. The function receives three arguments: The jqXHR (in jQuery 1.4.x, XMLHttpRequest) object, a string describing the type of error that occurred and an optional exception object, if one occurred. Possible values for the second argument (besides null) are "timeout", "error", "abort", and "parsererror". When an HTTP error occurs, errorThrown receives the textual portion of the HTTP status, such as "Not Found" or "Internal Server Error."

so the error callback must only be used to treat error that belong to the HTTP status not your own validation rules.

Sign up to request clarification or add additional context in comments.

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.