LetMeAnswerThis
LetMeAnswerThis

Reputation: 159

JQuery If Else statement never executed

I'm using a simple if else statement to check for response from a POST form.

This is weird: I can check for response in form of error. Using elseif: or else: just does absolut nothing. Even though the response is valid.

Current code:

post_data = {
    'someData': someData
}

// Ajax post data to server
$.post('register.php', post_data, function(response) {

    if (response.type == 'error') {
        if (response.errorType == 'something') {
            $("#someThing").addClass('has-error');
        }
    } else {
        window.location.reload(true);
    }

}, 'json');

This is so weird. I've tried to insert alerts to really check if the else statement ran in background or something.

When the response is: "error" the error statement is executed.

However when the response is: success/done/cleared/failed etc. (whatever i try) nothing happens.

I receive the respond in console - but JQuery doesnt run the } else { ... statement.

Upvotes: 2

Views: 102

Answers (1)

BesLoi
BesLoi

Reputation: 171

Actually its not what you think.

The function is only called on Success. For error handling you have to chain another function

For example try this:

post_data = {   
            'someData':someData
        }

        // Ajax post data to server
        $.post('register.php', post_data).done(function (response) {
            // This is your success function
             window.location.reload(true);
        })
       .fail(function (xhr, textStatus, errorThrown) {
            console.log("Post error: " + errorThrown);
            $("#someThing").addClass('has-error');
        });

I hope this help you to understand that weird behavior :P

jQuery documentation have different handling functions for different jQuery version. so better to use $.ajax

Upvotes: 1

Related Questions