Zain Malik
Zain Malik

Reputation: 9

Pass JS variable from one page to other

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

Upvotes: 2

Views: 114

Answers (1)

michaelitoh
michaelitoh

Reputation: 2340

You can do this by saving you data in localStorage o sessionStorage and then retrieve it in the other page. For example:

sessionStorage.setItem(SOME_KEY, VALUE_YOU_WANT_TO_SAVE);

and in the other page just retrieve it by calling:

var data = sessionStorage.getItem("THE_SAME_KEY_USED_BEFORE");

Now, data is has the data you were trying to pass.

I hope this help!

Upvotes: 1

Related Questions