php - else not working in javascript
Get the solution ↓↓↓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?
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}
beforeelse
will 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");
}
}
Answer
Solution:
You forgot after
{-code-2}
but should be
if(ajax.readyState == 4 && ajax.status == 200)
//
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.
Share solution ↓
Additional Information:
Link To Answer People are also looking for solutions of the problem: installation failed, reverting ./composer.json and ./composer.lock to their original content.
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.
Similar questions
Find the answer in similar questions on our website.
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.