Code after function executing before function completes
<p>At least I think that is what's happening. I have code in a .js file that calls a function existing in another .js file.  This function makes an ajax call to a php page that creates and returns a list of radio buttons with one selected.  When the function returns, code gets executed that passes the value of the selected radio button to a php page and generates some more lists (again via ajax).  Every time the user changes the selected radio button, the lists get updated.  This works when I select them via clicking, however, when the page loads, the proper radio button is selected, but the code to capture the selected radio button returns undefined.  When I place an alert directly after the function call it works properly.  This leads me to believe things are executing out of order.</p>

<p>The way I worked around this before was to place the code after the first function call in a function and call that function at the end of the first function.  However, this doesn't help with my understanding of why this is happening.  Here is the code:</p>

<p>First file:</p>

<pre><code>$(document).on("pageinit","#add_page",function(){
     restore_addreg_page();
     //alert('function finished');
     var selected_group = $('#group :checked').val();
}
</code></pre>

<p>Second file:</p>

<pre><code>function restore_addreg_page(){
    get_major_groups();
        ...more code
}
function get_major_groups(){
$.ajax({
    url: 'PHP_Scripts/get_major_groups.php',
    dataType: 'html',
    success: function(data){
        $('#major_groups').empty();
        $('#major_groups').append(data);
        $('#major_groups').trigger('create');
        $('input:radio').each(function(){
            if($(this).attr("id") == 'major_group0'){
                $(this).prop("checked",true).checkboxradio('refresh');
            }
        });
    },
    error: function(data){
        alert('Query Error');
    }
});
}
</code></pre>

<p>If I uncomment the alert, everything works correctly otherwise selected_group is undefined and the calls after that depend on that fail.  </p>
