I have a function to get a users lat long. I need to get that to return a url based on users location the url will differ. The returned url is used in a ajax call. However this second ajax call is getting hit before my first function finishes which then gives a 404 as the url is undefined.
so my code is:
$(document).ready(function () {
   getLatLong();
   if (!hasTicket) {
        doAction();
    } else {
        doAnotherAction();
        $.unblockUI();
    }
});
function doAction() {
         $.ajax({
            url: url, // this is where I am failing
            type: 'POST',
            success: function (response) {
                ticket = response.data.ticket;
                $.unblockUI();
            },
            error: function (xhr) {
                $.unblockUI();
                errorHandler("Failed" + xhr.status);
            }
        });
}
function getLatLong() {
    if (Modernizr.geolocation) {
        navigator.geolocation.getCurrentPosition(
            function (position) {
                getUrl(position.coords.latitude, position.coords.longitude);
            },
            getUrlFallback,
            { enableHighAccuracy: false, timeout: 10000, maximumAge: 360000 }
        );
    } else {
        getUrlFallback();
    }
}
function getUrl(latitude, longitude) {
    $.ajax({
        url: 'api/Controller/Action',
        type: 'GET',
        async: false, // tried making this synchronous
        data: {
            latitude: latitude,
            longitude: longitude
        },
        success: function (data) {
            url = data;
        },
        error: function (xhr) {
            errorHandler("Failed to get users nearest url: " + xhr.status);
        }
    });
}
So I call getLatLong which then calls my getUrl ajax function which has async set to false however I think it is returning from getLatLong first as my doAction function gets called and the url is then getting undefined.
How can I ensure that getLatLong and getUrl fully finish before the doAction gets run?
I tried to copy the functionality which happens after the call to getLatLong(); into a function and using $.when adn .then as below but it is still getting into the doAction method before the url is getting set.
function callAction() {
       if (!hasTicket) {
            doAction();
        } else {
            doAnotherAction();
            $.unblockUI();
        }
}
and then I had the below in doc ready:
$(document).ready(function () {
    $.when(getLatLong()).then(callAction());
});
EDIT - updated with the getUrlFallback function
function getUrlFallback () {
    // uses 3rd party geoPlugin
    getUrl(geoplugin_latitude(), geoplugin_longitude());
}
 
    