user1556433
user1556433

Reputation:

How to retain javascript array while page refresh?

PHP file

<input type="text" id="txtMyText">
<button type="button" id="myButton" onclick="addItemToArray()">Add to Array</button>

Javascript file

var myArray = []

function addItemToArray()
{
    myArray.push(document.getElementById("txtMyText").value);
}

Whenever I enter some value in a text field and hit the button, value gets stored in the array. When a page is refreshed, my array becomes empty. I want to retain its elements until I remove them manually. How do I retain them? Should I put array in PHP session or hidden field? If yes, then how?

Upvotes: 2

Views: 7080

Answers (5)

Suman Bogati
Suman Bogati

Reputation: 6349

Use localStorage API for this purpose, Use setItem() method and do stringify the array before storing into the localStorage. You can retrieve the stored item by getItem() and parse the stored array using JSON.parse(), something like

if(localStorage.getItem('textValues') == null){
    var myArray =[];
}else{
    myArray =  JSON.parse(localStorage.getItem('textValues'));
   //-----------^parse the item by getting---^--stored item
}

function addItemToArray(){
    myArray.push(document.getElementById("txtMyText").value);
    localStorage.setItem('textValues', JSON.stringify(myArray));
    //------------^store the item by stringify--^
}

DEMO

Upvotes: 4

andrew
andrew

Reputation: 9583

probably the easiest way would be using jQuery cookie

edit var myArray = [] /edit

if ($.cookie('arrayItems')){
      myArray=JSON.parse($.cookie('arrayItems'));
}


 function addItemToArray()  
 {
   myArray.push(document.getElementById("txtMyText").value);
  $.cookie('arrayItems',JSON.stringify(myArray));
 }

Upvotes: 1

I wrestled a bear once.
I wrestled a bear once.

Reputation: 23379

If you want to use a PHP session, I would take advantage of AJAX. You'll need to create a file to handle the array as you create it. Here's a simple example.

Your first page

<?php 
    //start the PHP session to save your array in
    session_start(); 
?>

<script type="text/javascript">
var myArray = [];
<?php
    if(isset($_SESSION['myArray'])) {
        foreach($_SESSION['myArray'] as $item){
            // prepopulate the session array from PHP
            echo "myArray[] = ".$item.";";
        }
    }
?>
function addItemToArray(){
    var addvalue = document.getElementById("txtMyText").value;
    myArray.push(addvalue);
    if (window.XMLHttpRequest){  var xmlhttp=new XMLHttpRequest();  }else {  var xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");  }
    xmlhttp.onreadystatechange=function()  {
      if (xmlhttp.readyState==4 && xmlhttp.status==200)    {
            document.getElementById("myDiv").innerHTML += xmlhttp.responseText .", ";
        }
    }
    xmlhttp.open("GET","save_array.php?newValue="+,true);
    xmlhttp.send();
}
</script>

<div id="show_my_array">
    <?php
        //show array saved from last time
        if(isset($_SESSION['myArray'])) {
            foreach($_SESSION['myArray'] as $item){
                // prepopulate the session array from PHP
                echo $item.", ";
            }
        }
    ?>
</div>
<input type="text" id="txtMyText">
<button type="button" id="myButton" onclick="addItemToArray()">Add to Array</button>

save_array.php

<?php
session_start();
if(!isset($_SESSION['myArray'])){
    $_SESSION['myArray'] = array();
}
$_SESSION['myarray'][] = $_GET['newValue'];
echo $_GET['newValue'];
?>

Upvotes: 1

CodeMaster
CodeMaster

Reputation: 15

To retain it on refresh you are going to need to store in local storage. localStorage.setItem("storageName", myArray) then to retrieve it localStorage.getItem("storageName") or var myArray = localStorage.getItem("storageName")

Upvotes: 1

000
000

Reputation: 27247

You could use the browser's internal storage: https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage

Store the array:

sessionStorage.setItem("items", JSON.stringify(items));

Get the array from storage:

var items = JSON.parse(sessionStorage.getItem("items"));

Upvotes: 2

Related Questions