2

Currently I have the following button:

<button class="button" type="button" onClick="javascript:window.location.href='test2.html'">Home</button>

Its a simple redirect. My page has a function getValues(), getValues2() both of which return an array.

a) I want my Home button to redirect to the given page and pass in the values from getValues(), getValues2()

b) I also want to use this passed value in the redirected page so how will I be able to access it? Use it in the sense that I want to loop over both the arrays and display them on my html page.

Thank you so much for any help.

1

1 Answer 1

1

I hope I understood your question correctly. To persist data you can use SessionStorage. It can only persist JSON values, and it get emptied once a user have closed the browser window. If you don't like this behavior, you can use LocalStorage, which saves data across sessions.

Here's JS:

function onRedirect() {
  sessionStorage.setItem("values", JSON.stringify(getValues()));
  sessionStorage.setItem("values2", JSON.stringify(getValues2()));
}

function getValues() {
  return [1, 2, 3];
}

function getValues2() {
  return ["hello", "world"];
}

function renderList(arr) {
  return arr.map(item => `<li>${item}</li>`).join("");
}

document.querySelector("button").addEventListener("click", onRedirect);

if (window.location.pathname === "/test2.html") {
  const values = JSON.parse(sessionStorage.getItem("values"));
  const values2 = JSON.parse(sessionStorage.getItem("values2"));

  document.querySelector(".values").innerHTML = renderList(values);
  document.querySelector(".values2").innerHTML = renderList(values2);
}

and here's HTML:

<html>

<head>
    <title>Parcel Sandbox</title>
    <meta charset="UTF-8" />
</head>

<body>
  <button class="button" type="button" onClick="javascript:window.location.href='test2.html'">
    Home
  </button>

  <ul class="values">
  </ul>

  <ul class="values2">
  </ul>

    <script src="src/index.js"></script>
</body>

</html>

Codesandbox: https://codesandbox.io/s/km2o2xv3pr

Sign up to request clarification or add additional context in comments.

3 Comments

Works so far. Is it possible to use these array values in a php code for some backend processing before rendering it on html?
Sorry, I don't use PHP so can't answer that question
Can you give any input on this : stackoverflow.com/questions/51580765/…

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.