变量“encontrado”在回调函数后具有“未定义”值

I have this code:

JavaScript:

function foo(callback){
    var producto = $("#inpt-producto").val();

    var ajax = new XMLHttpRequest();
    var url = "file_products.php"; // It will return 1 or 0
    var params = "producto=" + producto;
    ajax.open("POST", url, true);


    ajax.onreadystatechange = function() 
   {
        if(ajax.readyState == 4 && ajax.status == 200) {

            callback(ajax.responseText);

        }
    };

    ajax.send(params);
}

PHP:

$objectProduct = new product_Model(); 
$option = $objectProduct->existProduct($codProduct); // return 1 or 0 
echo $option

It Works fine for me. But the next code didn't work.

var encontrado = foo(function(result){ // I need store it in "encontrado" variable.
   console.log(result);//Actually return 1 or 0 value
});
console.log(encontrado); //Return Undefined :-(

The file file_products.php return 1 or 0.

The variable encontrado didn't store data. It is equal to "Undefined". I need store PHP value return. I have been working hard but didn't found the solution.

What can I do to fix it ? Any idea ?

Thanks.

In this case, the variable encontrado is being set to the return of the foo function, but the foo function doesn't return anything at all, so it's undefined. I'm going to assume you want encontrado to be set to the result of the ajax call, so the following code is what you'd do.

var encontrado;
foo(function(result){
    encontrado = result;
    console.log(encontrado);
});

Now, keep in mind encontrado will still be undefined unless the callback has happened, so don't try to use it until the callback has been executed.

Additionally, you were probably expecting encontrado to be the result of the callback, but that's not how javascript works. It would have been set to the return value of the foo function instead. And to clear up any possible confusion, console.log does not return any value it just outputs it to the console, to return a value actually do return some_variable;.

This is parcial solutions, works ok. But it uses "async:false".

if(producto!=""){
        encontrado = foo(); 
    }

    if(nombre==""){
         $("#messagesDiv").html("Field is empty");
         isValid = false;
    }else
     if(encontrado==1){
          $("#messagesDiv").html("Field is empty.");
          $("#inpt-producto").focus(); 
         isValid = false;
    }

    ......
    more validations....
    ......
    ......

   if(isValid){
    //Request and save data in Data base
  }



function foo() 
{

    var producto = $("#inpt-producto").val();
    var parameters = "producto=" + producto ;

    url = 'producto.php',

    ajax = new XMLHttpRequest(),
    u = null;

    ajax.open('POST', url, false);
    ajax.onreadystatechange = function()
    {
        if (ajax.readyState == 4)
        {
            if (ajax.status == 200){
                u = ajax.responseText;
            }
        }
    };

    ajax.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    ajax.setRequestHeader("Connection", "close");
    ajax.send(parameters);

    return u;
}

For now is ok. But I think change it and improve it. I found "Deferred Object" of jQuery. May be Works