Reputation: 742
so I do this:
function loginFunc(userNameOrEmail, passWord){
var emailOrUserNameV = encodeURIComponent(userNameOrEmail);
var passWordV = encodeURIComponent(passWord);
$.getJSON("http://mysite.com/pullData/login.php?callback=?",
{
emailOrUserName: emailOrUserNameV,
passWord: passWordV
},
function(recievedData) {
if(recievedData[0] == 'true'){
return true;
}
else{
return false;
}
});
}
then I do this:
$('#loginBtnHtml').click(function(){
var emailVar = $('#email_html').val();
var pwdVar = $('#password_html').val();
if(loginFunc(emailVar, pwdVar)){
alert('good');
}
else{
alert('bad');
}
});
If I run the loginFunc()
with an alert(recievedData[0]);
It works fine how do I get it to return bool to the $('#loginBtnHtml').click();
?
When I do this to troubleshoot:
$('#loginBtnHtml').click(function(){
var emailVar = $('#email_html').val();
var pwdVar = $('#password_html').val();
var whatIsBeingReturned = loginFunc(emailVar, pwdVar);
alert(whatIsBeingReturned);
});
it alerts with 'Undefined'... not sure what I'm doing wrong.
Upvotes: 0
Views: 169
Reputation: 191729
You can't return from ajax. Unless the ajax is synchronous (don't do it!) You cannot depend on the code executing in any particular order. All of the functionality that requires a response from ajax has to be in the ajax callback.
function loginFunc(userNameOrEmail, passWord){
...
return $.getJSON("http://mysite.com/pullData/login.php?callback=?",
}
$("#loginBtnHtml").on('click', function () {
//snip
loginFunc(emailVar, pwdVar).done(function (whatIsBeingReturned) {
console.log(whatIsBeingReturned);
});
});
Upvotes: 7
Reputation: 33972
Try a callback function instead. The AJAX happens ansync and the completion function can't return a value to the wrapping function.
function loginFunc(userNameOrEmail, passWord, callbackFn){
var emailOrUserNameV = encodeURIComponent(userNameOrEmail);
var passWordV = encodeURIComponent(passWord);
$.getJSON("http://mysite.com/pullData/login.php?callback=?",{
emailOrUserName: emailOrUserNameV,
passWord: passWordV
}, callbackFn);
}
$('#loginBtnHtml').click(function(){
var emailVar = $('#email_html').val();
var pwdVar = $('#password_html').val();
loginFunc(emailVar, pwdVar, function(recievedData){
alert(recievedData[0]);
});
});
Upvotes: 1
Reputation: 50493
The response of the JSON request is asynchronous. The logicFunc()
returns before the the response callback of the JSON request.
You need to write a callback method to handle the response. Something like:
function handleResponse(data){
// do something
}
function loginFunc(userNameOrEmail, passWord){
var emailOrUserNameV = encodeURIComponent(userNameOrEmail);
var passWordV = encodeURIComponent(passWord);
$.getJSON("http://mysite.com/pullData/login.php?callback=?",
{
emailOrUserName: emailOrUserNameV,
passWord: passWordV
},
handleResponse
});
}
Upvotes: 3