Skip to content Skip to sidebar Skip to footer

How To Retain Javascript Array While Page Refresh?

PHP file Javascript file var myArray = []

Solution 1:

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
}

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

DEMO

Solution 2:

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"));

Solution 3:

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")

Solution 4:

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(); 
?><scripttype="text/javascript">var myArray = [];
<?phpif(isset($_SESSION['myArray'])) {
        foreach($_SESSION['myArray'] as$item){
            // prepopulate the session array from PHPecho"myArray[] = ".$item.";";
        }
    }
?>functionaddItemToArray(){
    var addvalue = document.getElementById("txtMyText").value;
    myArray.push(addvalue);
    if (window.XMLHttpRequest){  var xmlhttp=newXMLHttpRequest();  }else {  var xmlhttp=newActiveXObject("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><divid="show_my_array"><?php//show array saved from last timeif(isset($_SESSION['myArray'])) {
            foreach($_SESSION['myArray'] as$item){
                // prepopulate the session array from PHPecho$item.", ";
            }
        }
    ?></div><inputtype="text"id="txtMyText"><buttontype="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'];
?>

Solution 5:

probably the easiest way would be using jQuery cookie

edit var myArray = [] /edit

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


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

Post a Comment for "How To Retain Javascript Array While Page Refresh?"