Reputation: 10163
This is my code, here I am passing input username and password values. I have written function that input will be checked with json file. If the given input exists "login correct" alert will be displayed else "login incorrect" will be displayed.
but here for me always "login incorrect" is displayed. I do know what wrong in this function. I have tried by using array variable in the function to hold the json file data. then it work correctly. I am having trouble in checking with json file.
help me solve this problem. My input should be checked with json file it exists or not.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js">
</script>
<script>
$(document).ready(function()
{
var a="user2";
var b="password2";
var checkval = false;
$.getJSON('login.json', function(data)
{
$.each(data,function(i,obj)
{
if(obj.username == a && obj.password == b)
{
checkval = true;
return false;
}
});
});
if(checkval == true)
{
alert("login correct");
}
else
{
alert("!!!!!-----Incorrect login Details-----!!!!!");
}
});
</script>
</head>
<body>
</body>
</html>
and this is my login.json file
[
{
"username": "user1",
"password": "password1"
},
{
"username":"user2",
"password" : "password2"
}
]
Upvotes: 0
Views: 3975
Reputation: 2620
ajax is async before the passwords and usernames are matched your code
if(checkval == true)
{
alert("login correct");
}
else
{
alert("!!!!!-----Incorrect login Details-----!!!!!");
}
is executed,try
$.getJSON('login.json', function(data)
{
$.each(data,function(i,obj)
{
if(obj.username == a && obj.password == b)
{
checkval = true;
return false;
}
});
if(checkval == true)
{
alert("login correct");
}
else
{
alert("!!!!!-----Incorrect login Details-----!!!!!");
}
});
here is a small proof of concept that when ajax is not used it works http://jsfiddle.net/aKVC2/
and here is the working DEMO
P.S.
as suggested by some answers setting async:false
is one option(never avail it!!!), but since jQuery version 1.8 its DEPRECATED
Upvotes: 1
Reputation: 1014
ajax is asynchronous ,Your function making call before it can check against the returned value
add below line just above the $.getJson
$.ajaxSetup({async:false});
Upvotes: 1
Reputation: 74738
Put the second if inside:
$.getJSON('login.json', function(data) {
$.each(data,function(i,obj){
if(obj.username == a && obj.password == b){
checkval = true;
return false;
}
});
if(checkval == true){
alert("login correct");
}else{
alert("!!!!!-----Incorrect login Details-----!!!!!");
}
});
Upvotes: 1
Reputation: 1390
$.getJSON is async.. meaning it makes the call while the rest of your code runs. It is getting to if(checkval == true) before the call is made and before it can check against the values returned.
If you want to "fix" this, see this question.
Is it possible to set async:false to $.getJSON call
Upvotes: 1