简体   繁体   中英

How to add items to javascript array that can be accessed on another page?

I have a problem. I have created a php website and with every item there is a "request a quote" button. on clicking the button, i want the item name to be added to an array (which i am doing through Javascript).subsequently, the array is to be added to the request form "message" field on contact.php. i have used this -

<script language="javascript">
// Empty array
var empty = [];

// Array containing initial elements.
var arrayitem= ['hello'];

alert(arrayitem[1]);
function myFunction(item) {
arrayitem.push(item);
var Items='';
for (var i = 0; i < arrayitem.length; i++) {
Items=Items+','+(arrayitem[i]);
   alert(Items);

};
document.getElementById("message").value=arrayitem[1];
}
</script>

on header.php page, which i include on every page. I have two more pages- 1. computers.php- that contains computers as items and 2. softwares.png- that contains softwares as items.

Now the problem is, when i add items from one page, they are appended to the array and it works fine, but when i navigate to another page, the items added from previous page get removed from the array ..and moreover i cant see the araay items in the "message field of contactus.php.".please help

JavaScript is a client side scripting language, it is not designed to persist variable values between page requests. If you want to access JavaScript variables on another page you will have to pass them along with the request for the new page, so that the new page can reinstate them.

Besides posting it to the next page along with the request, in newer browsers you can use localStorage:

// Store the array
var array = [1, 2, 3];
localStorage['array'] = JSON.stringify(array);

// Retrieve the array
var storedArray = JSON.parse(localStorage['array']);

In older and newer browsers you can use cookies:

// Store the array in a cookie
var array = [1, 2, 3];
var jsonArray = JSON.stringify(array);
setCookie('mycookie', jsonArray , 1);

function setCookie(name, value, days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = '; expires='+date.toGMTString();
  }
  else var expires = '';
  document.cookie = name+'='+value+expires+'; path=/';
}

// Retrieve the array from a cookie
var jsonArrayFrom Cookie = JSON.parse(getCookie('mycookie'));

function getCookie(name) {
  name += '=';
  var cookies = document.cookie.split(';');
  for(var i=0;i < cookies.length;i++) {
    var cookie = cookies[i];
    while (cookie.charAt(0)==' ') cookie = cookie.substring(1, cookie.length);
    if (cookie.indexOf(name) == 0) return cookie.substring(name.length, cookie.length);
  }
  return null;
}

You could try using the browser's localStorage to store data in between page visits.

Try this JavaScript in your header.php:

localStorage.setItem("preference", "10");

And then in your contact page try this:

console.log(localStorage.getItem("preference"));

You should see "10" in your browser console.

Here's more info about localStorage: http://diveintohtml5.info/storage.html

You should save the array and post it to the other page by using a form or other method. Javascript is not persisted.

You can use Webstorage for in-between pages persistence. Create a JSON object from your array like this:

var myArrayString = JSON.stringify(myArray);

And store it in a key in the webstorage:

sessionStorage.setItem('arrayStore',myArrayString);

You can read this key back in another page:

sessionStorage.getItem('arrayStore'); //returns 'myArrayString'

...or simply reference the sessionStorage object:

sessionStorage.arrayStore; //returns 'myArrayString'

Try to use cookies on javascript and then retrieve it on PHP with $_COOKIE var.

http://www.php.net/manual/en/features.cookies.php

Regards.

You could write the information into cookies via PHP and read them via JavaScript, in the example jQuery is assumed:

<html>
<head>
    <script src="http://code.jquery.com/jquery-1.9.1.min.js"/>
    <script src="http://cachedcommons.org/cache/jquery-cookie/0.0.0/javascripts/jquery-cookie.js"/>
</head>
<body>
<h1>Cookie</h1>
<?php
$expire = time() + 60 * 60 * 24 * 30;
setcookie('some_cookie', "fnord", $expire);
?>
<script type="text/javascript">
    console.log($);
    $(document).ready(function () {
        alert($.cookie("some_cookie"));
    });
</script>
</body>
</html>

If you only need to support modern browser, you better work with localStorage, there also libaries avaiable to prevent you from reinventing the wheel.

Thanks All for your solutions.. I have used sessionStorage to store the items. and retrieve them on the contact page. i am providing the code. may be it can help someone- included this in header.php-

<script language="javascript">

function myFunction(item) {
sessionStorage.setItem(item,item);
var keyval=sessionStorage.item;
for(var i = 0; i < sessionStorage.length; i++)  
{  
    var keyName = sessionStorage.key(i);  
    var itemvalue = sessionStorage.getItem(keyName); 
      alert(keyName + " = " + itemvalue);  


}  

}
</script>

and in contactus page-

 for(var i = 0; i < sessionStorage.length; i++)  
{  
    var keyName = sessionStorage.key(i);  
    var itemvalue = (i+1)+"-"+sessionStorage.getItem(keyName); 
     document.contact.message.value=document.contact.message.value+"\n"+itemvalue ;
}  

Hope it helps!!!! Thanks all!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM