0

I have two html pages that two javascript functions.

page1.html

<a href="page2.html" onclick="ex1()">link1</a>

page2.html

<a href="#" onclick="ex2()">link2</a>

jscript1.js

var abc;
function ex1() {
    abc='some text';
    console.log(abc);

}
function ex2() {
    console.log(abc);
}

In the console, I'm getting undefined when inside the ex2() function. What am I doing wrong here?

4 Answers 4

2

You're going to another page, where your abc variable isn't defined.

You need to render your variable persistent from one page to the other.

One solution is to use the localStorage :

function ex1() {
    localStorage['abc']='some text';
    console.log(localStorage['abc']);

}
function ex2() {
    console.log(localStorage['abc']);
}
Sign up to request clarification or add additional context in comments.

3 Comments

Sorry, by mistake I typed that var. Even without the var it is not working.
There was more than one error. See edit for the most important one.
Thank you so much, was stuck on this for a while, localStorage solved the problem :)
1

You are changing pages, which means you are loading a new execution environment.

the old variables are lost. You need to transfer them to the new page in the URL, or via cookie or storage.

Comments

1

Are you trying to pass value from page to page (page1.html -> page2.html)? If so it's not going to work as scripts are 'reset' with every page load...

You might use cookie(s) or localStorage to pass the variable - cookies are more crossbrowser friendly (local storage will not work in older browsers, Firefox will ask users for permissions).

Comments

0

If they are not included an in a common html or jsp or php , soon on. then the variable abc is initiated again. The scope of the variable is limited within the page and cannot be redirected to an other page.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.