php - else not working in javascript

418

here is my code

  $('#login').on('click',function(e){
    e.preventDefault();
    var username = document.getElementById('username').value;
    var password = document.getElementById('password').value;
    var ajax = new XMLHttpRequest();
    var vars = 'username='+username+'&password='+password;
    var url = "singInDrProcess.php";
    ajax.open("POST", url, true);
    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.send(vars);
    ajax.onreadystatechange = function() {
        if(ajax.readyState == 4 && ajax.status == 200) {
            var return_data = ajax.responseText;
            if(return_data!="success_login")
                document.getElementById("result_signin").innerHTML = return_data;
            }else{
                window.location.replace("profile.php");
                           }
        }
  });

The problem is , when user comes to this page and tries to Login, even if he never enters any username or password, and just clicks on my login button, page will be redirected to profile.php I mean, the ELSE part always runs, either there is data on fields or all of them are empty what is the problem?

233

Answer

Solution:

Indent your code according to your parenthesis:

{-code-2}-code-1}

That's not what you want.

Adding a{-code-2} after{-code-3} or removing the} beforeelsewill fix it:

if(ajax.readyState == 4 && ajax.status == 200) {-code-2}
    var return_data = ajax.responseText;
    if (return_data!="success_login") {-code-2}
        document.getElementById("result_signin").innerHTML = return_data;
    } else {-code-2}
        window.location.replace("profile.php");
    }
}
19

Answer

Solution:

You forgot after{-code-2}

but should be

 if(ajax.readyState == 4 && ajax.status == 200) 
 //     



705
votes

Answer

----add opening curly brace here---^
269

Answer

----add opening curly brace here---^
871

Answer

Solution:

if(return_data!="success_login")
            document.getElementById("result_signin").innerHTML = return_data;
        }else{
            window.location.replace("profile.php");
                       }
    }
});

should be changed to

if(return_data!="success_login")
            {document.getElementById("result_signin").innerHTML = return_data;
        }else{
            window.location.replace("profile.php");
                       }
    }
});

You forgot the { after the if parentheses.

Also, you should use JSHint, as it helps with errors and such.

People are also looking for solutions to the problem: PHP POST batch update

Source

Didn't find the answer?

Our community is visited by hundreds of web development professionals every day. Ask your question and get a quick answer for free.

Ask a Question

Write quick answer

Do you know the answer to this question? Write a quick response to it. With your help, we will make our community stronger.

Similar questions

Find the answer in similar questions on our website.