1

This is my code:

var j = 0;
var c = 0;
var riepvet = new Array();

function controllo() {

    if ((src1 == "") || (src1 == "undefined")) {
        alert("Selezionare un'immagine.");
    }
    else if(j==0) {
        riepvet[c] = src1;
        c++;
        for (var k = 0; k < c; k++) {
            alert(riepvet[k]);
        }
        location.href = "schienale.html";
        j++;

    }
    else if (j==1){
        riepvet[c] = src1;
        c++;
        for (k = 0; k < c; k++) {
            alert(riepvet[k]);
        }
        location.href = "riep.html";
        j++;
    }
}

What I need, is make the numeric variables j and c available through all the pages of my program. Is this possible using cookies (since they aren't string but numbers)?

I've already tried to use eval() but it seems not to work.

Any suggestions?

Edit:

 Cookies.set('j', 0);
var j = parseInt(Cookies.get('j'));

Cookies.set('imuno');
var imuno = Cookies.get('imuno');
Cookies.set('imdue');
var imdue = Cookies.get('imdue');

function controllo() {

    if ((src1 == "") || (src1 == "undefined")) {
        alert("Selezionare un'immagine.");
    }
    else if (j == 0) {
        imuno = src1;
        Cookies.set('imuno', src1);
        alert(imuno);
        location.href = "schienale.html";
        j++;
        Cookies.set('j', 1);

    }
    else if (j == 1) {
        imdue = src1;
        Cookies.set('imdue', src1);
        alert(imuno,imdue);
        location.href = "riep.html";
        j++;
        Cookies.set('j', 2);
    }
}

When i retrieve the function Controllo() the variable jdoes not mantain the value.

Francesco Monti
  • 151
  • 2
  • 10
  • *"since they aren't string but numbers"* - Numbers *can* be formatted as strings. And later turned back into numbers... – nnnnnn Feb 25 '16 at 10:03
  • http://stackoverflow.com/questions/14573223/set-cookie-and-get-cookie-with-javascript – mplungjan Feb 25 '16 at 10:04

2 Answers2

1

Are many ways to achieve that .

You can use cookies

Use a cookie for each key-value you want to store:

document.cookie = "myCookie=myValue";
document.cookie = "myOtherCookie=myOtherValue";

Store a single cookie with a custom serialization of your complex data, for example JSON:

document.cookie = "myCookie=" + JSON.stringify({foo: 'bar', baz: 'bar'});

or

you can use localStorage

localStorage.setItem('myvariable', 'myvalue');
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30
1

Yes, you could use cookies, i suggest js-cookie.

  • Create a cookie :

    Cookies.set('name', 'value');
    
  • Read cookie :

    Cookies.get('name'); // => 'value'
    

You could store you numbers as strings then cast them after get, e.g:

Cookies.set('j', j);  //Set j
j = parseInt( Cookies.get('j') );  //Get j

Example :

Cookies.set('j', 1); //Set j
var j = parseInt( Cookies.get('j') );  //Get j

if( j == 0 ){
    alert('Yes j == 0');
}else{
    alert('No j == '+j);
}

Hope this helps.

Zakaria Acharki
  • 66,747
  • 15
  • 75
  • 101