I created AJAX auto-complete from a JSON file
function run() {
    field.show();
    field.html('');
    let val = search.val();
    let input = new RegExp(val, "gi");
    $.get("js/pk.json").then(function(city) {
        if (val.trim().length === 0) {
            field.empty();
            field.hide();
        }
        $.each(city, function(key, value) {
            let n = new RegExp(val, 'gi');
            let name = value.city.replace(n, `<span class="me">${val}</span>`);
            if (value.city.search(input) != -1) {
                field.append(`<li class="list-search" data-name='${value.city}'><a href="pages/check.html" class="waves-effect">${name}  ${value.country}<br><br></a></li>`);
            }
        })
    })
});
and I want to pass "data-name" attribute clicked li tag value to div in another page.
That is :
$("#field").on("click", "li", function(e) {
    finalName=$(this).attr('data-name');
});
and the div is <div class="Fname"></div>.
The variable finalName is global but it shows undefined outside this click event.
I am not an expert but I think that is due to AJAX Asynchronous request which loads variable before it is assigned value. Can anyone please explain to me how it will work? I found other answers that were related to this but couldn't understand them. Thank you in advance
 
     
    