Remember javascript variable across more than one page - javascript

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.

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/

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,

Related

Storing a variable from an html document to display it in another

On the first page, the user is asked to select a name from a list (select/option tags) and click the "edit" button. User's choice is stored using the "option" variable and we redirect him/her to the next page.
When the body of the next page loads, it triggers the second function, which displays the option made previously as the main header of the page.
The problem is that, although onEdit() runs, displayOption() displays the variable as the empty string (as declared above the functions).
Why doesn't the second function "see" the alteration?
var option = "";
//"edit" button (onclick)
function onEdit() {
var selector = document.getElementById("selector");
option = selector.options[selector.selectedIndex].value;
window.location.href = "nextPage.html";
return false;
}
//"nextPage.html" body (onload)
function displayOption() {
var header = document.getElementById("header-main");
header.innerHTML = option;
}
Use local storage for that, it is easy to use and in this case highly appropriate.
See mdn docs
Example
on first page simply declare
localStorage.setItem('option', 'selectedOption');
on the second page get the var
var option = localStorage.getItem('option');
EDIT
as wendelin commented it is even more appropriate to use session storage, because it remove itself automatically.
The reason this doesn't work is that when nextPage.html loads, the entire script is re-evaluated, and option is now back to its default value of "".
You'll need another solution to persist the user's choice across refreshes. One of the more common approaches to something like this is to set the value as a query string parameter that can be read from within displayOption.

setting a variable in javascript to be used in another form

I have form with a Grid (telerik), i think the technology behind it doesnt matter. I let user click on a row in the grid. During the click I extract a value from the Grid with Javascript, like so:
function RadDrillDoubleClick(sender, eventArgs) {
var Code = eventArgs.getDataKeyValue("Status");
if (Code == "In Progress" || Code == "")
{
location.href = "Main1.aspx?mode=edit&DID=" + eventArgs.getDataKeyValue("D_ID");
}
else {
location.href = "Main1.aspx?mode=view&DID=" + eventArgs.getDataKeyValue("D_ID");
}
}
After user has clicked the grid, I call this JS function and send them to correct .aspx page with either VIEW or EDIT mode dependent directly on the Code.
What I'm trying to do is once I get to the Main1.aspx page, I want to be able to continue to hold the CODE value, because when users performs a certain action, I'll need to call a javascript function and use the actual CODE to determine what the user will be able to do.....
var Code = eventArgs.getDataKeyValue("Status");
is there any way I can somehow create like a GLOBAL Variable called
CodeValue
that I can pass around to another form without doing it in the URL?
When the browser navigates to a page, all current JavaScript is unloaded from the browser. This means any functions/variables, etc. will not be accessible on the new page unless you've persisted the value in some way.
Common ways of persisting the value include:
Add it to the query string of the URL the user is navigating to
Save the value to a cookie
Save the value to local/session storage
For your scenario, #1 is probably your best bet (keep in mind the user can have multiple browsers/tabs open to your site).
One way to get the value from URL is like this: on the page Main1.aspx, you add to your JavaScript a function that will run after page loads and that will get what it needs from the current URL
var globalValue; // variable that will receive the value from URL
window.onload = function() {
var thisURL = window.location.href;
globalValue = url.split("?").pop();
// this will store in globalValue everything that comes after the last "?"
// example: if the url is www.site.com/text?value, it will store string "value" to globalValue
};

in which file can I put a script to erase the caches of the Titanium application

I wrote a script that allows you to delete a property in the caches of the application, however I need to run this script only once when I install the application.
someone has an idea, thanks
var executed = 0;
if(executed === 0){
Ti.App.Properties.removeProperty("My_Property");
executed++;
}
The only ways you can hold some value across app sessions are Ti.App.Properties or sql database. So you can do it in two ways as below:
Solution 1: Use another property to know that you have deleted the desired property.
// for first time installation, the default value (or 2nd parameter) will be false as you have not deleted the property yet
var isDeleted = Ti.App.Properties.getBool('My_Property_Deleted', false);
if (isDeleted) {
Ti.App.Properties.removeProperty("My_Property");
// since you have deleted it, now set it to true so this 'if' block doesn't runs on any next app session
Ti.App.Properties.setBool('My_Property_Deleted', true);
} else {
// you have already deleted the property, 'if' block won't run now
}
Solution 2: Create a new database or pre-load a shipped db with your app.
// Titanium will create it if it doesn't exists, or return a reference to it if it exists (after first call & after app install)
var db = Ti.Database.open('your_db');
// create a new table to store properties states
db.execute('CREATE TABLE IF NOT EXISTS deletedProperties(id INTEGER PRIMARY KEY, property_name TEXT);');
// query the database to know if it contains any row with the desired property name
var result = db.execute('select * from deletedProperties where name=?', "My_Property");
if (result.rowCount == 0) { // means no property exists with such name
// first delete the desired property
Ti.App.Properties.removeProperty("My_Property");
// insert this property name in table so it can be available to let you know you have deleted the desired property
db.execute('insert into deletedProperties(name) values(?)', "My_Property");
} else {
// you have already deleted the property, 'if' block won't run now
}
// never forget to close the database after no use of it
db.close();
There can be other ways as well, but these 2 will work for what you want. Read more about Ti.Database here

How to access and use multiple data from json object? Do I need to make an array?

I am a beginner and using $.get to retrieve data from a rest API such as:
[{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},
{"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}
{"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}] }
$.get('http://xxxxxxxxxxx,
function (data) {
var obj = $.parseJSON(data);
So from what I understand I have retrieved the data from the REST API and parsed it so it is stored in a variable called obj.
My question is, how do I access and use each unique record in the obj variable?
Each record has it's own picture (item1.jpg, item2.jpg etc).
Whem my app loads I want it to show the item1.jpg image, and I want to be able to navigate to the other item pictures using buttons (previous / next).
I also want the description and price to be displayed underneath in some text input fields.
What I have figured so far is that I should:
Iterate through the obj variable, and store each record into an array.
Upon app initialisation I can set the default value for the image placeholder to array[index0].url, and set the description and price fields.
I can then set the previous and next buttons to array[currentIndex-1] or array[currentIndex+1].
Would this be the best way to do it?
Or can I just do this without using an array and manipulate the obj.data directly?
Thanks!!!
I may not be understanding what exactly what you want to do but I think I have the gist. If you just want to show the picture then the array of just images probably wouldn't be a bad idea. However, it looks like the Jason you're getting is already in an array. You can just use array index notation to get to what you want.
ie)
var arr = //your json response ;
var current = 0; //sets currently displayed object to the first in the array
var setCurrent = function () {
var image = arr[current]["url"];
}
You can then modify current however you want (on click on arrow iterate up/down, etc) then call the setCurrent function to set your image the the one you want. Hope that helps!
You can use the response you have from $.get() directly.
It is an array of objects.
You can use it like this:
console.log(data[2].description);
// outputs: "Console"
I've made a CodePen demo where it has a 4th object with a real image url to show you how to use the url info...
EDIT
Just in case you wouldn't know this:
You can use the response inside the scope of the $.get() callback...
You can not use it straith after the $.get() outside the callback since $.get() is asynchronous.
You can use it in some other handler wich will happen after the response is received.
var getResponse;
$.get('http://xxxxxxxxxxx', function (data) {
getResponse = data;
console.log(data[2].description);
// outputs: "Console"
console.log(getResponse[2].description);
// outputs: "Console"
});
console.log(getResponse[2].description);
// outputs: "Undefined"
// But since this handler will be triggered long after the response is obtained:
$("#somebutton").click(function(){
console.log(getResponse[2].description);
// outputs: "console"
});
In order for your page javascript to be able to access the data retrieved from your ajax request, you'll need to assign it to some variable which exists outside the callback function.
You will need to wait until the ajax request has been processed before you can read the array. So you might want to set the actual default image to be something that doesn't rely on the ajax request (a local image).
Here's a simple approach
// fake testing ajax func
function fakeget (url, callback) {
setTimeout(callback(JSON.stringify([
{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"}, {"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"},
{"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}
])), 1000);
}
// real code starts here
// global variables for ajax callback and setImg func to update
var imageData, currentImg;
// change this back to $.get for real
fakeget('http://xxxxxxxxxxx',
function (data) {
imageData = $.parseJSON(data);
setImg(0);
}
);
function setImg(index) {
// turns negative indices into expected "wraparound" index
currentImg = (index % imageData.length + imageData.length) % imageData.length;
var r = imageData[currentImg];
$("#theImg").attr('src', r.url);
$('#theDescription').text(r.price + " " + r.description);
}
$("#prev").click(function () {
setImg(currentImg - 1);
});
$("#next").click(function () {
setImg(currentImg + 1);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>
<img id='theImg' src='somedefault.jpg'>
<div id='theDescription'></div>
</div>
<button id='prev'>Prev</button>
<button id='next'>Next</button>
Few observations :
Your JSON Object is not a valid JSON.
No need to parse it again your data is already a JSON Object.
Working fiddle
var data = [{"id":"1","url":"http:\/\/123.456.78.910\/workforce\/images\/item1.jpg","price":"99","description":"Mobile Phone"},{"id":"2","url":"http:\/\/123.456.78.910\/workforce\/images\/item2.jpg","price":"98","description":"Laptop"}, {"id":"3","url":"http:\/\/123.456.78.910\/workforce\/images\/item3.jpg","price":"92","description":"Console"}];
for (var i in data) {
var imgUrl = data[i].url;
console.log(imgUrl);
}

How to save html data local

How can I save my HTML element tag data after user closed the browser. For example
<div class="classOne" data-random="50">
And i used jQuery to change the data attribute
$(".classOne").attr("data-random","40")
And if the user close out the browser and comes back the value for data-random will be 40. How can I achieve this ?
Have you tried looking at localStorage?
LocalStorage allows you to store data within the browser. So even after the user close out the browser and comes back, you still have the value stored in your LocalStorage
Here is a sample code on how you can use local storage:
localStorage.setItem("data-random", 40);
You can set it with:
localStorage.setItem("data-random","40")
And later load it:
localStorage.getItem("data-random")
If you want to store JSON objects, you should use stringify() before saving and JSON.parse() after loading.
try localStorage.
https://developer.mozilla.org/ko/docs/Web/API/Window/localStorage
$(document).onload(function(){
if(localStorage.rendomData){
var data = localStorage.rendomData - 10
localStorage.set(randomData,data)
}
else{
localStorage.set(randomData,50)
}
})
I hope this helps.
The easiest way to achive it is to use cookies. Just take this plugin: https://github.com/carhartl/jquery-cookie and then above the line:
$(".classOne").attr("data-random","40")
add:
var randValue;
if (typeof $.cookie('my-rand-value') == undefined) {
// generate random value
randValue = generateRandomValue //assign random value to variable
$.cookie('my-rand-value', randValue)
}
else {
randValue = $.cookie('my-rand-value')
}
at the end change static value to your variable:
$(".classOne").attr("data-random",randValue)
You can do that by using cookies as well as by using local storage -
for local storage first store first try to get value if it is stored like -
if(localStorage.getItem("data-random") != null){
return localStorage.getItem("data-random");
} else {
return 50;
}
and when user changes the value you can save that value by -
localStorage.setItem("data-random", value);
Use Jquery function beforeunload and save it into localStorage.
$(window).on('beforeunload', function() {
// Put the object into storage
localStorage.setItem('data', $(".classOne").attr("data-random"));
});
To Retrieve the data from storage whenever your page opens.
var retrievedData = localStorage.getItem('data');

Categories