Reputation: 3246
js:
function verificaExistPed(numped){
var valida;
jQuery.post("procedures/class_oc.php", // ajax post
{
cache : false,
checkYear : true,
numped : numped
},
function(data)
{
if(data === "s"){
valida = true;
}else{
valida = false;
}
}
)
return valida;
}
and, calling the function in another place, should return valida
result inside variable check
, in my case, true
or false
.
var check = verificaExistPed('".$numped."');
alert(check); // always undifined
but, always undefined.
how can i set valida
to true
or false
from a $.post
callback ?
Upvotes: 0
Views: 1242
Reputation: 19217
You cannot return from as jQuery.post
is an asynchronous call. You have to rely on a callback function in order to get the response from server. Try this:
function verificaExistPed(numped, isValidCallback){
jQuery.post("procedures/class_oc.php", // ajax post
{
cache : false,
checkYear : true,
numped : numped
},
function(data)
{
isValidCallback(data === "s");
}
)
}
USAGE:
verificaExistPed('".$numped."', function(isValid) {
alert(isValid); //returns true or false
});
Upvotes: 1
Reputation: 30095
It's because handler are invoked asinchronously after your functon invoked. So you synchronously request for it, like:
function test() {
var html = $.ajax({
url: "procedures/class_oc.php",
async: false // <-- heres the key !
}).responseText;
return html;
}
Upvotes: 2