"send data with window.location.href and get"

How to send data with window.location.href and get?

Have you ever needed to send data from one page to another without using a form or AJAX? One way to do this is by using the window.location.href method. This method allows you to redirect to a new URL while passing data in the query string of the URL.

Sending Data with window.location.href

To send data with window.location.href, you need to append the data to the URL as a query string. The query string starts with a question mark (?) and is followed by key-value pairs separated by an ampersand (&).


const data = {
  name: 'Raju',
  age: 25,
  profession: 'Blogger'
};

const queryString = Object.keys(data)
  .map(key => key + '=' + encodeURIComponent(data[key]))
  .join('&');

const url = 'https://example.com/page.html?' + queryString;

window.location.href = url;

The code above creates an object called data with three properties: name, age, and profession. It then maps the object keys to their values and encodes them using the encodeURIComponent function. Finally, it joins the key-value pairs with an ampersand separator and appends them to the URL.

Getting Data from window.location.href

To get the data from window.location.href, you need to parse the query string and extract the values of the key-value pairs.


const queryString = window.location.search.slice(1);

const data = queryString.split('&').reduce((acc, curr) => {
  const [key, value] = curr.split('=');
  acc[key] = decodeURIComponent(value);
  return acc;
}, {});

console.log(data);

The code above gets the query string from window.location.search and removes the leading question mark. It then splits the string into key-value pairs using the ampersand separator and reduces them into an object with the keys as the property names and the values as the property values. Finally, it logs the object to the console.

Multiple Ways to Send Data

There are other ways to send data besides window.location.href. One popular method is using AJAX to send data asynchronously without reloading the page. Another method is using cookies or local storage to store data on the client-side.

Conclusion

Using window.location.href to send data is a simple and effective way to pass data between pages without using a form or AJAX. Remember to encode and decode the data when sending and receiving it to avoid any issues with special characters.

Subscribe to The Poor Coder | Algorithm Solutions

Don’t miss out on the latest issues. Sign up now to get access to the library of members-only issues.
[email protected]
Subscribe