0

I am constructing a Javascript variable in my code after some user interaction. I am trying to send that constructed JS object to another page.

I am trying to send it via HREF using

<a href="newpage.html?" + jsvariable">

But this one fails. Is there any other way to accomplish this ?

thanks

1
  • You have mismatched quotes Commented Aug 23, 2015 at 17:39

3 Answers 3

1

You cannot inject variables from javascript like that.

But you may pick up that anchor and manipulate its href attribute. There are many ways to do this.

Example:

... your html
<a id="someAnchor" href="newpage.html">test</a>

<script>
    document.getElementById("someAnchor").href += "?someParam=" + jsvariable;
</script>
... rest of your html

P.S.: Make sure the value of jsvariable is url-encoded.

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

Comments

0

Given that the data comes from user input, you'll want to make sure to protect against malicious inputs.

Try something like:

var anchorEl = // reference to your anchor.
anchorEl.href += '?data=' + encodeURI(jsvariable)

Note, the above solution works in cases where you want further user interaction to get to the next page. If you want to redirect the page directly, you can do:

window.location.href = 'newpage.html?data=' + encodeURI(jsvariable)

Comments

0

I haven't tested this but I think it will work:

  1. Convert your object to JSON:

    var jsonObject = JSON.stringify(jsvariable);
    
  2. Then pass it into your url:

    <a href="newpage.html?" + jsonObject>
    
  3. At your newpage.html, read the URL and extract the information that you need

    var jsParameter = ...
    
  4. Convert JSON back to JS object:

    var jsObject = JSON.parse(jsParameter);
    

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.