2

I am new to javascript, i am trying to make a small site with two HTML pages (A and B) and a global js file.

So lets say i have selected certain items in page A, the list-preview on Page A gets updated. But if i want to see the list in detail i have to go to page B.

Page A and B bith use the same .js file, the selected items are saved in a array.

How do i make sure the selected items still stay in the array, and the array doesn't get flushed when i go from page A to page B ?

what i thought of was ...

var selectedProductsName = new Array();

in OwnJS.js the adding items to the preview list works. i'm only struggling to keep the array unflushed when i go to page B from page A.

MrMe TumbsUp
  • 416
  • 1
  • 4
  • 17
  • 3
    You can't. That JS file will be reloaded when loading each page, so the array gets reset. You can store the info in `localStorage` or `sessionStorage` to persist it, or use a backend. – tymeJV Apr 02 '14 at 17:55
  • Another option would be to serialize the array and put it in a hidden field (for browsers that don't support localStorage and sessionStorage) – ElGavilan Apr 02 '14 at 18:01

3 Answers3

1

HTML5 introduces a new thing called localStorage. It's basically some kind of storage that is persistent between all pages of your website as well as between user sessions. It can be accessed as a simple key/value store:

var selectedProductsName = localStorage.getItem("selectedProductsName");

And to set:

localStorage.setItem("selectedProductsName", []);

Here's an article about getting started with localStorage, if you want to be able to do more things like checking browser compatibility for localStorage and watching the storage event, among others.

Michael Tang
  • 4,686
  • 5
  • 25
  • 24
  • do i still have to define it as a array() ? – MrMe TumbsUp Apr 02 '14 at 18:01
  • 1
    Check out this [stackoverflow question](http://stackoverflow.com/questions/885156/whats-wrong-with-var-x-new-array) on using array literals (`[]`) vs the `new` keyword. Basically it's preferred to use the literal `[]` (and, for objects: `{}`) over the `new` keyword. – Michael Tang Apr 02 '14 at 18:06
  • 1
    so i read about localStorage abit and it seems that it can only storage STRINGS. i would have to use JSON.stringify() and JSON.parse() if i wanted to use arrays – MrMe TumbsUp Apr 02 '14 at 20:00
  • That should be fine, unless you're storing functions in the array (which, if you are trying to save functions to `localStorage`, shame on you). – Michael Tang Apr 02 '14 at 21:39
0

You could use the HTML5 local storage. It lets you tell the browser to save data on the user's machine. (There's also session storage, valid only for the current session.) Save (in Apply.html)

IN.API.Profile("me")
.fields(["id", "firstName", "lastName", "pictureUrl","headline","industry","location:(name)","positions:(title)","emailAddress"])
  .result(function(result) {
      profile = result.values[0];

      // save all keys to local storage
      for (f in profile) localStorage[f] = fields[f];

      // more stuff ...
  });

to Retrieve (in personal_Info.html)

// retrieve first name from local storage
var firstName = localStorage["firstName"];
if (firstName !== undefined) {
    $("#textfield1").attr(value, firstName);
}
Terabyte
  • 455
  • 2
  • 12
0

Source Page The Source Page has an HTML Button with a jQuery Click event handler. When the Button is clicked, the values of the Name TextBox and the Technology DropDownList is set as QueryString Parameter and then the page is redirected to the Destination page (Page2.htm).

<input type="button" id="btnQueryString" value="Send" />
<script type="text/javascript">
    $(function () {
        $("#btnQueryString").bind("click", function () {
            var url = "Page2.htm?name=" + encodeURIComponent($("#txtName").val()) + "&technology=" + encodeURIComponent($("#ddlTechnolgy").val());
            window.location.href = url;
        });
    });
</script>

Destination Page On the Destination page (Page2.htm), inside the jQuery Page Load event handler the URL of the page is first checked to determine whether it has some QueryString Parameters being received, this is done by checking the window.location.search property. If it has some QueryString Parameters then loop is executed and each QueryString Key and Value Pair is inserted in an Array and finally the values are displayed on the page using the HTML span.

<script type="text/javascript">
    var queryString = new Array();
    $(function () {
        if (queryString.length == 0) {
            if (window.location.search.split('?').length > 1) {
                var params = window.location.search.split('?')[1].split('&');
                for (var i = 0; i < params.length; i++) {
                    var key = params[i].split('=')[0];
                    var value = decodeURIComponent(params[i].split('=')[1]);
                    queryString[key] = value;
                }
            }
        }
        if (queryString["name"] != null && queryString["technology"] != null) {
            var data = "<u>Values from QueryString</u><br /><br />";
            data += "<b>Name:</b> " + queryString["name"] + " <b>Technology:</b> " + queryString["technology"];
            $("#lblData").html(data);
        }
    });
</script>
Terabyte
  • 455
  • 2
  • 12