Redirecting with variables in javascript


#1

Hi guys,

I’m very very new to javascript and i’m trying to make a website where i can input data and then the website will redirect me to the next appropriate page (based off the data in the variables) when i click a button.

My question comes in 2 parts:

  1. Can i create an index file where all my variables are stored and the data can be edited on multiple pages in my website?
  2. How can i redirect to different pages based off of the data stored in these variables?

any help would be appreciated!


#2

Hi @aaron51connelly, variables per se can only be accessed while the script is actually running; but you can persist (string) data using the local storage (or session storage for the current session only). For example:

window.localStorage.setItem('contactURL', 'https://my-site.com/contact')

// And then on any other page of your site
var contactURL = window.localStorage.getItem('contactURL')

By setting the location:

window.location = window.localStorage.getItem('contactURL')

#3

Thanks man! Would there be anything different if my variables were numerical values?


#4

Well anything you store will get coerced to a string, so e.g. the number 42 will get stored as "42". You can however cast it to a number again using Number(); and plain (serializable) objects and arrays can be stored as JSON, e.g.

var myArray = [1, 2, 3]
window.localStorage.setItem('myArray', JSON.stringify(myArray))

// Somewhere else
var myArray = JSON.parse(window.localStorage.getItem('myArray'))