I'm using AJAX to get a current post data for 'Store'. And I'm using AJAX to call the data for all stores, so that I can run a distance check with turf.js to show the 3 closest nearby stores to the current post/Store. But of course, I can't access the arrays of store or stores outside of the success function due to variable scope being restricted to just the success function.
jQuery(document).ready(function( $ ) {
let cur_store_id = $('#map').attr('data-store-id');
// Get Current Store Data
$.ajax( {
type: 'GET',
url: '/champlainfarms/champlain-farms/wp-json/champlain/v1/store/' + cur_store_id,
} ).success( function( data ) {
store = data;
} );
// Get all Store to calculate nearest Stores
$.ajax( {
type: 'GET',
url: `/champlainfarms/champlain-farms/wp-json/champlain/v1/stores/`,
} ).success( function( data ) {
stores = data;
console.log('Pulled All Stores');
)};
// Returns variable not specified as scope doesn't allow variable out
if (stores.length > 0 ) {
console.log ("There is more than 20 locations in Stores");
}
)};
How do can I pass the store or stores variable outside of the AJAX .success()
? I understand AJAX is asynchronous, so how do I wait till the data is returned and then work with with it outside of the .success()
?