Aiden Zhao
Aiden Zhao

Reputation: 574

How should I handle validation error using Ajax?

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:

My concern is:

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!

Upvotes: 1

Views: 510

Answers (1)

kabstergo
kabstergo

Reputation: 771

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.

Upvotes: 1

Related Questions