-1

Lets say i have a JSON {"ID":"1","Name":"XYZ"} I want to encode this data and send it to new page say new.html and display this data as ID: 1 Name: XYZ. How can I achieve this?

Till now i've tried this:

url = 'new.html?' + encodeURIComponent(window.btoa(JSON.stringify(str)));
document.location.href = url;

This code is in my first.html script tag. In my new.html I tried this:

<div id='here'></div>
        <script>
            window.onload = function () {
                var url = document.location.href,
                    params = url.split('?')[1].split('&'),
                    data = {}, tmp;
                    console.log(JSON.parse(window.atob(params)));
                for (var i = 0, l = params.length; i < l; i++) {
                    tmp = params[i].split('=');
                    data[tmp[0]] = tmp[1];
                }
                document.getElementById('here').innerHTML = data.id;
            }    
        </script>

But in console.log i'm getting an error: Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded.

Aditya
  • 85
  • 12
  • 1
    Possible duplicate of [Convert JSON into uri-encoded string](https://stackoverflow.com/questions/9909620/convert-json-into-uri-encoded-string) – Felix Lemke Feb 06 '19 at 11:13
  • 1
    The `btoa` is pointless, but shouldn't prevent you from achieving your goal. What's the problem? – Quentin Feb 06 '19 at 11:14
  • hi @Quentin, i've updated my question. please check. – Aditya Feb 06 '19 at 11:18
  • 1
    If the object has only one one dimension, you could add all the params to the url as key-value pairs: url?param1=value1&param2=value2... – Sergio Tx Feb 06 '19 at 11:24
  • actually @SergioTx this data is from web service so i don't know what data will be returned from there. – Aditya Feb 06 '19 at 11:27

1 Answers1

1

Failed to execute 'atob' on 'Window': The string to be decoded is not correctly encoded

Look at how you encoded it:

encodeURIComponent

You have to reverse that with decodeURIComponent

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • what i did is replaced this line: `JSON.parse(window.atob(params)` with `JSON.parse(decodeURIComponent(params)` and it gave me an error, so i removed `JSON.parse` sorry I thought data got decoded but when i saw in debug i realized it didn't. Sorry it was my mistake. – Aditya Feb 06 '19 at 11:46