0

I have a database and 2 drop down menus, using javascript I obtain the value from the selected drop down, and then send it to my PHP, the PHP then brings back information from the database and displays it in a table, there are two tables as there are 2 drop downs. Here is my javascript:

    function choice1()
    {    
     var x = document.getElementById("select1");
     a = x.options[x.selectedIndex].value;
     window.location.href = "index.php?a=" + a + "&b=" + b; 
    }

    function choice2()
    {    
     var y = document.getElementById("select2");
     b = (y.options[y.selectedIndex].value);
     window.location.href = "index.php?a=" + a + "&b=" + b; 
    }

what happens is it waits for both drop downs to change before changing both of the tables, what I would like it to do is change the table as soon as one changes but keep the other one the same. This I think means the javascript variable a or b needs to be stored so that when the page changes it can be called upon so that the PHP gives the same information for the second table.

user3603650
  • 57
  • 1
  • 1
  • 4

2 Answers2

1

You can persist data in many ways:

Examples are:

cookies: Javascript getCookie functions and https://developer.mozilla.org/en-US/docs/Web/API/document.cookie

localStorage, get variables, hidden input.

I recommend using the localStorage for this case (html5), because it's pretty safe and easy to use.

//    getter function of 'persistent' variables.
function getPersistent(myVar) {
    //    ensure the localStorage object exists.
    //    return the variable we are looking for if it does or: undefined.
    return (window.localStorage)? localStorage.getItem(myVar) : undefined;
}

//    setter function of 'persistent' variables.
function setPersistent(myVar, value) {
    //    ensure the localStorage object exists.
    if (window.localStorage) {
        //    set the variable.
        localStorage.setItem(myVar, value);
    }
}

//    first run (page refresh) returns undefined.
//    second run returns 4.
console.log(getPersistent('test'));

//    we set the localStorage var 'test' to '4'.
//    note that localStorage only saves strings.
//    so you need to parse/convert the data if you want to modify.
console.log(setPersistent('test', '4'));

//    returns localStorage var 'test' ==> 4.
console.log(getPersistent('test'));

fiddle: http://jsfiddle.net/kychan/2WJX4/

Community
  • 1
  • 1
Kai
  • 1,156
  • 8
  • 18
0

The simplest way to persist values across pages is to use the session storage API. It's much like local storage, but is torn down when the current window / session closes.

Of course, you could always just opt for updating your page by AJAX rather than reloading the document entire,

Jimmy Breck-McKye
  • 2,923
  • 1
  • 22
  • 32