-1

EDITED I have readed the answer suggested as duplicate, but I'm asking one more level. I created my answer based on what I had learn searching previously and the duplicate one bring me to my question.

I've got this function that is working

function validateLimit(dia, hora, cel, vit, kg) {
  var params = 'cel='+cel;
    params += '&viti='+viti;
    params += '&dia='+data[2]+"-"+data[1]+"-"+data[0];
    params += '&hora='+hora;
    params += '&kg='+kg;

  function testAjax(handleData) {
    $.ajax({
      type: "POST",
      url: "recheck-limit.php",
      data: params,
      datatype: "json",
      success: function(d) {
        handleData(d);
      }
    });
  }

  testAjax(function(output) {
    var data = JSON.parse(output);
    if(data.disponible == true) {
      return "1234";
    } else {
      return "4321";
    }
  });
  return "aser";
}

I call it from outside like that

hay_dispo = validateLimit(dia, hora, cel, viti, kg);

But I don't know how to receive the value "1234" or "4321" from inside textAjax function, I can return "aser", but can't get the values I need depending on the value of data.disponible. Thank you

Bernardao
  • 466
  • 6
  • 23

1 Answers1

0

am i missing sth or would it work like that, i just added a callback

  function validateLimit(dia, hora, cel, vit, kg, callback) {
    var params = 'cel='+cel;
      params += '&viti='+viti;
      params += '&dia='+data[2]+"-"+data[1]+"-"+data[0];
      params += '&hora='+hora;
      params += '&kg='+kg;

    function testAjax(handleData) {
      $.ajax({
        type: "POST",
        url: "recheck-limit.php",
        data: params,
        datatype: "json",
        success: function(d) {
          handleData(d);
        }
      });
    }

    testAjax(function(output) {
      var data = JSON.parse(output);
      if(data.disponible == true) {
        callback("1234");
      } else {
        callback("4321");
      }
    });
    return "aser";
  }

  validateLimit(dia, hora, cel, viti, kg, function(val){
    hay_dispo = val; 
    // ...continue
  });
john Smith
  • 17,409
  • 11
  • 76
  • 117
  • It's not working, it's returning me "aser", I need to return 1234 or 4321 – Bernardao Sep 08 '14 at 15:21
  • I don't know where I have to define the callback("1234) function – Bernardao Sep 08 '14 at 15:43
  • its the last argument passed to validateLimit, as you can see on the very bottom i pass a function as last argument that gets one argument e.g "1234" or "4321" – john Smith Sep 08 '14 at 16:18
  • it should alert "1234" or "4321" when callback is called – john Smith Sep 08 '14 at 16:19
  • I saw later the callback at validateLimit Yes the alert or console.log is working, but I can't assign the value to a variable, how could I do it? – Bernardao Sep 08 '14 at 16:53
  • I used your update, and it's not working. Updated in the validateLimit definition, and also in the calling and adding callback("1234"), but not working, empty value – Bernardao Sep 08 '14 at 17:38