1

I want to send a variable from JavaScript to another HTML page and be redirected to that page, but I can't use forms because the first page is purely in JavaScript and a .js file so I can't declare a form. I also can't use the URL as my data is too big. What are other options? Every tutorial I've found uses either forms or the URL. Is there an alternative?

Based on this answer, I used the following code:

function post(array) {
    var method = "post"; 
    var form = document.createElement("form");
    form.setAttribute("method", method);
    form.setAttribute("action", "helloworld.html");

    var hiddenField = document.createElement("input");
    hiddenField.setAttribute("type", "hidden");
    hiddenField.setAttribute("name", "array");
    hiddenField.setAttribute("value", array);

    form.appendChild(hiddenField);

    document.body.appendChild(form);
    form.submit();
}

and I call post(parameter) in another method.

It successfully redirects to helloworld.html, but how can I get the variable that I passed?

Community
  • 1
  • 1

3 Answers3

0

You can make an HTTP request from JavaScript:

// jQuery
$.get("demo_test.asp", function(data, status){
        // do something
});

jQuery documentation is located here

TheDude
  • 3,591
  • 2
  • 26
  • 47
0

You can use jQuery ajax API and send the data through POST request. See more: here or here

Edit: oops, I didn't notice that you don't have any server side handler enabled. In that case, if you do not want to use forms you can handle get/url parameters with jQuery.param() or use some routing enabling library.

rylek90
  • 1,572
  • 1
  • 8
  • 10
0

You can save the data in the localStorage and if the second page is in the same domain. The data has to be string.

Page One:

function sendData(){
    localStorage.setItem("data", data);
    location.href = "helloworld.html";
}

Save the data.

Page Two:

function onLoad(){
    var data = storage.getItem("data");
}

Read the data.

Optional: You could also create a JSON Object and save it with the function JSON.stringify

Graham
  • 6,577
  • 17
  • 55
  • 76
winner_joiner
  • 3,643
  • 4
  • 32
  • 48