0

I am begginer. In my code validStatus is a variable. Which i returned at end of function. this validStatus is not set to true/ false value inside jquery $get() callback function. how can i set variable and return that variable.

function isOpeningyearValid(openingyear) {
    //openingyear is valid . when it is First Fiscal year
    var validStatus;
    var url = "/Inventory/InventoryOpeningStock/isOpeningyearValid?openingyear=" + openingyear;
    $.get(url, function (res) {
        if(res.validStatus == true)
        {
            successNotify("yes first fiscal year");
            validStatus = true;
        }
        else {
            errorNotify("not first fiscal year");
            validStatus = false;
        }
    });
    console.log("validation status",validStatus);
    return validStatus;
}

please note that: errorNotify(); and successNotify(); is executing according to the if(res.validStatus == true). but only validStatus is not set to any value. i think its a variable scope problem.

Toha
  • 5
  • 3
  • Because of deferred execution the return will usually run **before** the call is finished. You're better off creating a global variable and setting that to true or false (like you are currently) and not having the function return anything. – Mathew Thompson Jun 21 '23 at 12:45
  • Also see [this question.](https://stackoverflow.com/questions/23667086/why-is-my-variable-unaltered-after-i-modify-it-inside-of-a-function-asynchron) – Pointy Jun 21 '23 at 12:45
  • @MathewThompson that is incorrect. The `return` will **in all cases** return before the `$.get()` callback runs. And a global variable won't really help (always) as the rest of the code won't know when the value is eventually set. – Pointy Jun 21 '23 at 12:54
  • @Pointy fair, I did actually write all originally but retracted to usually incase someone came back with a curveball case lol. – Mathew Thompson Jun 21 '23 at 13:03
  • @Pointy you are right global is not working – Toha Jun 22 '23 at 03:57

0 Answers0