0

I'm a javascript newbie and I'm trying to call a jQuery function in this way:

function getProducts(){
      $.post("products.php",
      {
        customer_ID:$("#customers").val()
      },
      function(data,status){
        return status && data !== "";
      });
};

$(document).ready(function(){
    $("#customers").change(function(){
        if(getProducts){
            alert("trovato");

            $("#products").prop("disabled", false);
            $("#products").html(data);
        }else{
            alert("non trovato");

            $("#products").empty();
            $("#products").prop("disabled", true);
        }
    });
});

The if-else statement in the ready doesn't work although the function getProducts works properly. The problem, I suppose, is in the function call. What am I wrong with this? Thank you.

superpuccio
  • 11,674
  • 8
  • 65
  • 93

2 Answers2

0

You need to wrap the response with a callback, like so:

function getProducts(callback){
      $.post("products.php",
      {
        customer_ID:$("#customers").val()
      },
      function(data,status){
         callback(status && data !== "");
      });
};

$(document).ready(function(){
    $("#customers").change(function(){
        getProducts(function(status) {
           if(status){
             alert("trovato");

             $("#products").prop("disabled", false);
             $("#products").html(data);
           }else{
             alert("non trovato");

             $("#products").empty();
             $("#products").prop("disabled", true);
           }
        });

    });
});
Hless
  • 3,326
  • 20
  • 22
  • 1
    I think that the syntax of these javascript things is a bit messy, but yes, this is the solution :) – superpuccio Feb 04 '14 at 09:03
  • What is messy about it exactly? I forgot a few spaces but smashed this together in a few seconds. The way the callback gets passed around isn't messy though, it's how javascript works.. – Hless Feb 04 '14 at 09:05
  • Nono, it's clear and it's ok! I didn't "argue" with you or with your solution, but with the javascript syntax (the javascript Modus Operandi) – superpuccio Feb 04 '14 at 09:08
  • Yeah I guess it's a bit weird if you're a javascript beginner (or new to functional programming for that matter). But you'll get used to it after a while. – Hless Feb 04 '14 at 09:10
-1

I'm not quite sure if this will work because of the asynchronized call inside of the function.

The obvious mistake is that you have to call a function like that: function(). You just forgot the parentheses.

If it won't work after that fix, you have to rework your program to use callbacks where you have asynchron calls.

markusthoemmes
  • 3,080
  • 14
  • 23