I have the following code. So basically the JavaScript needs to look at the username and password and check it via an API (which works) and returns true or false. True giving the user access to the next page and false reloading the login page.
Everything works perfectly except for the JavaScript if statement.
My code is as follows:
var ApiKey = ''; //generated API Key
var userPass = document.getElementById('pass'); //gets the password
var userName = document.getElementById('usr'); //gets the username
function testAJAX(){
$.getJSON("http://mywebsitesapiaddress.com/api" + ApiKey +"&user="+ userName.value + "&pass=" + userPass.value, function(data) {
if (data.success == "true") {
window.location = "mainpage.html";
}
else {
location.reload();
}
});
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<input type="text" name="username" id="usr" placeholder="Enter your username">
<input type="password" name="password" id="pass" placeholder="Enter your password">
<button onclick="testAJAX()" id ="login">Login</button>
Your code looks fine, except for the type of the success
property value.
It could be that the server is not returning a string literal 'true'
instead a boolean value true
so
if (data.success) { //or data.success === true
window.location = "mainpage.html";
} else {
location.reload();
}
When JSON data is true or false. Double quotes cannot be used.
Thank you for the quick responses. Turns out the problem was that the datatypes are clashing, I changed the API response to 1 and 0 and that seemed to have solved the problem. Easier and more flexible when using numbers.
var ApiKey = ''; //generated API Key
var userPass = document.getElementById('pass'); //gets the password
var userName = document.getElementById('usr'); //gets the username
function testAJAX(){
$.getJSON("http://mywebsitesapiaddress.com/api" + ApiKey +"&user="+ userName.value + "&pass=" + userPass.value, function(data) {
if (data.success == 1) {
window.location = "mainpage.html";
}
else {
location.reload();
}
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.