I've tried to understand Callbacks, but perhaps I'm not getting it. Yes, I have looked at How to write a jQuery function with a callback?, How to return value from an asynchronous callback function? and at this explanation and have tried to model my code based on the examples there. I even read this tutorial but it looks like I am having trouble understanding the concept. Or maybe it is just some small error...
Just for context, I am trying to create a simple Login/Signup form where I make sure people don't signup twice and also send them to signup when they try to login when they are not signed up, etc...
Here's the HTML:
<div id="LoginSignup">
<form>
<p id="LoginSignupMesg">Signup or Login</p>
<input type="text" id="LoginID" placeholder="Phone/Email" size="10" value="" />
<input type="password" id="password" placeholder="Password" size="10" value="" />
<input type="button" value="Login" id="Login" />
<input type="button" value="Signup" id="Signup" />
</form>
</div>
and here's one version out of many that I have tried of the code:
var xsl ="";
function idcheck(id, pwd, callback) {
$.ajax("ls.php?l='" + id + "'&p='" + pwd + "'", {
success: function(data) {
if (typeof callback === "function") {
callback(data);
} else {alert("Not a function!")}
},
error: function() {
alert('The file failed to load!');
},
type: 'POST'
});
// return xsl;
}
function c(d){
xsl = d;
}
$(document).ready(function() {
$("#Login").click(function(event) {
var x = $("#LoginID").val();
var y = $("#password").val();
idcheck(x, y, c);
alert('Login: ' + xsl);
});
});
$(document).ready(function() {
$("#Signup").click(function(event) {
var x = $("#LoginID").val();
var y = $("#password").val();
idcheck(x, y, c);
alert('Signup: ' + xsl);
});
});
If I click either, the Login or Signup buttons, I get a blank string the first time and if I click either one after that, I get the SQLData from the ajax call. Once the data shows in the alert box, it shows no matter how many times I click.
I have also tried returning the value from idcheck as you can see from the commented out line, and also using:
xsl = idcheck(x, y, c);
but nothing seems to give me the data I want. What am I dong wrong?