0

I have a function in my code that gets a value for variable appID, like so:

$.post("/jqf/updfam_processajax.php", {ADULT: answer1, CHILD: answer2}, function (data77) {
    var obj77 = $.parseJSON(data77);
    appID = obj77[0].idlinksAppID;
});

I'd like to use the value of that variable later on in my code in a seperate function, like so:

$.post("/jqf/updfam_processajax.php", {PID3a: appID}, function (data20) {
    var obj20 = $.parseJSON(data20);
    $(obj20).each(function (index) {
        $('#ParentHCACYrs').children("option[value=" + obj20[index].parenthcacyrsYear + "]").prop('selected', true);
    });
});

I have defined the appID variable above the first function as blank, but when I console.log the value of the variable I get a good value inside the top function but I get 'undefined' when trying to use the value in the second function. I was under the impression this would work, but apparently not. I have reviewed info on this but can't seem to find the right information. Any help please?

EDIT

The code now reads as such:

$.post("/jqf/updfam_processajax.php", {ADULT: answer1, CHILD: answer2}, function (data77) {
    var obj77 = $.parseJSON(data77);
    appID = obj77[0].idlinksAppID;
    $.post("/jqf/updfam_processajax.php", {PID3a: appID}, function (data20) {
        var obj20 = $.parseJSON(data20);
        $(obj20).each(function (index) {
                                    $('#ParentHCACYrs').children("option[value=" + obj20[index].parenthcacyrsYear + "]").prop('selected', true);
        });
    });

    $.post("/jqf/updfam_processajax.php", {PID4: appID}, function (data21) {
        var obj21 = $.parseJSON(data21);
        $(obj21).each(function (index) {
            $('#ParentHCACLangs').children("option[value=" + obj21[index].parenthcaclangsLang + "]").prop('selected', true);
        });
    });
 });

When I use Chrome developer tools, I don't see the 2 sub-posts going through...

TheJester1977
  • 155
  • 1
  • 10
  • Are these functions in the same file/class? – Marco Santarossa Aug 30 '16 at 21:43
  • 2
    The two pieces of code are asynchronous. If you are calling them one after the other,t hen `appID` may or may not have been assigned by the time the second one runs. Most likely wouldn't. – VLAZ Aug 30 '16 at 21:44
  • It's *asynchronous*, you can't use the value you get back in the first ajax call outside that ajax call. – adeneo Aug 30 '16 at 21:44
  • appID would only be set upon successful completion of the first Ajax call. The second function parsing happens immediately, so the empty value will be used. – jedifans Aug 30 '16 at 21:45

0 Answers0