0

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.

Saurav Rastogi
  • 9,575
  • 3
  • 29
  • 41
Gregory
  • 1
  • 2
  • Show some php code – wscourge Dec 10 '16 at 02:49
  • Hi @wscourge. This is part of (not all) PHP script. I tested it and Works awesome. require ....... $objectProduct = new product_Model(); $option = $objectProduct->existProduct($codProduct); // return 1 or 0 echo $option; – Gregory Dec 10 '16 at 04:50
  • //In Javascript side ajax.onreadystatechange = function() { if(ajax.readyState == 4 && ajax.status == 200) { callback(ajax.responseText); } }; I tested it and works fine. To watch the PHP results I used Console of Firefox. It returned the correct values. The problem is in Javascript side. – Gregory Dec 10 '16 at 05:04

2 Answers2

0

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;.

djdduty
  • 274
  • 1
  • 8
  • Another error in your code, which is unrelated, is that you aren't adding the `params` string to your ajax request, you might want to make sure the parameters get added to the request properly before sending the request. – djdduty Dec 10 '16 at 02:58
0

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

Gregory
  • 1
  • 2