Is there a better way to get data from localStorage after storing the data without refreshing/reloading the page - json

I'm trying to make a button that could store the data to the localStorage. After storing the data, I want to get the data without refreshing/reloading the page
The way I use to fix this case is, I put 2 commands on a button. The first command is to store the data, and the second command is to get the data using $scope to make it easy to display it on the page
Here is my code
$scope.storeData = function(){
if(localStorage.getItem('value') === null){
// The value that will set to the localStorage
$scope.data = 'Selamat sore';
// To set the value on $scope.data to localStorage
localStorage.setItem('value', JSON.stringify($scope.data));
//To get the value and display it on the page
$scope.getData = JSON.parse(localStorage.getItem('value'));
}else{
$scope.getData = JSON.parse(localStorage.getItem('value'));
}
}
It's actually working, but maybe there is a better way to do this
Thanks

I find this cleaner, and simpler.
function MyController($scope) {
// if value is null a default 'Selamat sore' is set
$scope.data = localStorage.getItem('value') || 'Selamat sore';
$scope.saveData = function() {
localStorage.setItem('value', JSON.stringify($scope.data));
}
}

Related

How to define a variable that's gonna be retrieved from localstorage (Chrome extension)?

I have a variable defined like this (not sure if it should be with let or var in the first place):
let activated = false;
The first thing that the extension should do is check the value of activated. I think this is the correct syntax:
chrome.storage.local.get(['activated'], function(result) {
activated = result.activated
alert ("activated: " + result.activated)
});
After some logic, I want to change activetedto true, with this syntax:
chrome.storage.local.set({activated: true}, function() {
console.log("activated changed to true: " + activated)
});
However, when I close and open the browser again, activatedis set to false again.
How should I structure this in order to achieve the desired result?
The way to acess a localstorage variable isn't by defining as I was doing in let activated = false;.
The way to add the variable retrieved from localstorage to the program's control flow should be done this way:
chrome.storage.local.get(['activated'], function(result) {
if (result.activated == value) { // Do something }
});

angularjs save rendered values in html in a variable

I hope someone can help me with this, It's a strange question maybe as I didn't find an answer online.
I call the database and retrieve a list (in json) of items.
Then in angularjs,I render this list by extracting relevant pieces of data(name,age,etc) and show it properly in a table as a list of rows.
I have then an edit button that takes me to another page where I want to put a dropdown list.
What I want to know if is possible to add to that dropdown list the rendered list I previously created in my previous page.
is it possible to save the previously rendered list in a variable and then use that variable in the dropdown?
thank you
You could store the list within a controller and make this data availablte to this dropdown, I think.
Instead of trying to query for the list, add the list to the template, get the list from the template and render somewhere else, I'd suggest query for the list, save the list in a service , and then when you want to use that list again, get it from the service. Something like:
service:
var services = angular.module('services');
services.factory('getListService',['$http',function($http){
var getListOfStuff = function(){
//call to database
return //your json
};
var extractNameAgeEtc = function(){
var myListOfStuff = //get list of stuff from $http or database
var myListOfNameAgeEtc = //make a list of tuples or {name,age,etc} objects
return myListOfNameAgeEtc;
};
return {
extractNameAgeEtc : extractNameAgeEtc
};
}]);
controllers:
angular.module('controllers',['services']);
var controllersModule = angular.module('controllers');
controllersModule.controller('tableRenderController',['getListService','$scope',function(getListService,$scope){
//use this with your table rendering template, probably with ng-repeat
$scope.MyTableValue = getListService.extractNameAgeEtc();
}]);
controllersModule.controller('dropdownRenderController',['getListService','$scope',function(getListService,$scope){
//use this with your dropdown rendering template, probably with ng-repeat
$scope.MyDropDownValue = getListService.extractNameAgeEtc();
}]);

Getting Current Data from KendoUI TreeView

I'm using a kendo UI tree with a remote data source from a JSON file.
I have a button on the tree page which gets the current data of the tree,sends it through a POST to a server and the server saves the current data to the JSON file so as the next time I reload the page,the changes I made will be kept.That's what I want to happen.
So I know the current data of the tree is in:
$("#treeview").data("kendoTreeView").dataSource.data()
Which means the data changes real time in there for example when someone drag and drops a node of the tree.
My problem starts when this data doesn't seem to change when I drag and drop nodes inside the tree,and only changes when I drag and drop a node on the root level of the tree and even then it doesn't do it correcly as the node should be moved in there as well but instead the node gets copied,leaving the past node in the tree as well...
For Example I have this tree:
If I make a drag and drop change like this:
And I send the data,save it and reload the change isn't made at all!
PS:Even when I view the current data after the change before sending it,I see that there is no change on the data at all even though I did a change visualy with a drag and drop.So it doesn't have to do with the sending,saving and the server.
On the other hand,if I make a change like this:
I can see in the current data that the moved node is added in the end of the data indeed but it is not deleted from it's initial position within the data!So if i send the current data to the server,save it and then refresh I get the result:
The code for viewing and sending the data is:
function sendData() {
var req = createRequest();
var putUrl = "rest/hello/treeData";
req.open("post", putUrl, true);
req.setRequestHeader("Content-type","application/json");
var dsdata = $("#treeview").data("kendoTreeView").dataSource.data();
alert(JSON.stringify(dsdata));
req.send(JSON.stringify(dsdata));
req.onreadystatechange = function() {
if (req.readyState != 4) {
return;
}
if (req.status != 200) {
alert("Error: " + req.status);
return;
}
alert("Sent Data Status: " + req.responseText);
}
}
Is this a Bug or am I doing something wrong?Has anyone been able to see the current data changing correctly on every drag and drop?
First and most important you have to use the latest version of KendoUI (Kendo UI Beta v2012.3.1024) still in beta but is where they have solved many problems.
Then, when you create the kendoTreeView you have to say something like:
tree = $("#treeview").kendoTreeView({
dataSource :kendo.observableHierarchy(data),
dragAndDrop:true
}).data("kendoTreeView");
Here the important is not using directly data array but wrapping it with kendo.observableHierarchy.
Then you will have the data updated with the result of drag & drops.
For me in addition to OnaBai answer I had to use the sync function on the save method. I am using Type Script.
this.treeData = new kendo.data.HierarchicalDataSource({
data: kendo.observableHierarchy([]),//Thanks OnaBai
schema: {
model: {
id: "MenuItemId",
children: "MenuItemChildren",
hasChildren: (e) => {
//this removes arrow next to items that do not have children.
return e.MenuItemChildren && e.MenuItemChildren.length > 0;
}
}
}
});
public save() {
this.treeData.sync().done(() => {
console.log("sync data");
var myType = this.treeData.view();
this.$http.post("/api/TreeViewPicker", myType)
.then((response) => {
});
});
}

JSON results into a variable and store in hidden input field

I wrote code below that is working perfectly for displaying the results of my sales tax calculation into a span tag. But, I am not understanding how to change the "total" value into a variable that I can work with.
<script type="text/javascript">
function doStateTax(){
var grandtotalX = $('#GRANDtotalprice').val();
var statetaxX = $('#ddl').val();
$.post('statetax.php',
{statetaxX:statetaxX, grandtotalX:grandtotalX},
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
// ...
});
return false;
};
</script>
Currently, $('.total-placeholder').html(data.total); is successfully placing the total number into here:
<span class="total-placeholder"></span>
but how would I make the (data.total) part become a variable? With help figuring this out, I can pass that variable into a hidden input field as a "value" and successfully give a proper total to Authorize.net
I tried this and id didn't work (see the testtotal part to see what I'm trying to accomplish)..
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
$testtotal = (data.total);
// ...
If you are using a hidden field inside a form, you could do:
//inside $.post -> success handler.
$('.total-placeholder').html(data.total);
$('input[name=yourHiddenFieldName]', yourForm).val(data.total);
This will now be submitted along with the usual submit. Or if you want to access the data elsewhere:
var dataValue = $('input[name=yourHiddenFieldName]', yourForm).val();
The "data" object you are calling can be used anywhere within the scope after you have a success call. Like this:
$.post('statetax.php',
{statetaxX:statetaxX, grandtotalX:grandtotalX},
function(data) {
data = $.parseJSON(data);
var total = data.total;
var tax = data.total * 0.19;
});
return false;
};
Whenever you get an object back always try to see with an alert() or console.log() what it is.
alert(data); // This would return <object> or <undefined> or <a_value> etc.
After that try to delve deeper (when not "undefined").
alert(data.total); // <a_value>?
If you want 'testotal' to be recognized outside the function scope, you need to define it outside the function, and then you can use it somewhere else:
var $testtotal;
function(data) {
data = $.parseJSON(data);
$('.products-placeholder').html(data.products);
$('.statetax-placeholder').html(data.statetax);
$('.total-placeholder').html(data.total);
$testtotal = (data.total);
EDIT:
The comments are becoming too long so i'll try and explain here:
variables defined in javascript cannot be accessed by PHP and vice versa, the only way PHP would know about your javascript variable is if you pass it that variable in an HTTP request (regular or ajax).
So if you want to pass the $testtotal variable to php you need to make an ajax request(or plain old HTTP request) and send the variable to the php script and then use $_GET/$_POST to retrieve it.
Hope that answers your question, if not then please edit your question so it'll be clearer.

taking values separately using local storage in html5

I am making an app in html5.It is like a quiz based app. I am randomly fetching questions from the XML and displaying it one by one.I am using page navigation for that. After completing and submitting your answer u will switch to other page.if once i submit my answer i cannot attempt it back. but i can see the feedback and score on switching to that page that is my problem. I have display that feedback and score and to store it in local storage. i am able to do local storage but values that i am getting is overriding. so i am getting last submitted value.Now my concern is to divide that values navigation number wise.right now what is happening if i submit my answer and suppose i am at navigation number 3 n i am looking at navigation part 1 then there also i am getting last submitted value not the part 1 value.Please give ur suggestion and help me out for that.
Here is the code snippet:
//for navigation of pages
$(document).ready(function (){
/*$(document).bind("contextmenu",function(e){
return false;
});*/
var obj;
total=x.length;
for(var j=0;j<x.length;j++)
{
if(j==0)
{
$("#navigationlist").append('<li>'+(j+1)+'</li>');
display_nav(j,$("#selected_link"))
}
else
$("#navigationlist").append('<li>'+(j+1)+'</li>');
}
$("#next").bind("click",function (){
$(".navg").each(function(index){
if($(".navg").length==(i+1))
{
if(index==0)
obj=$(this);
}
else
{
if(index==(i+1))
obj=$(this);
}
});
for(var j=0;j<xmlDoc.getElementsByTagName("question").length;j++)
{
xmlDoc.getElementsByTagName("question")[j].removeAttribute("status");
}
$("#btnSubmit").attr("disabled","false");
$("#btnSubmit").attr("onclick","checekAnswer()");
display_nav(0,obj)
}
else
display_nav((i+1),obj)
});
});
and
correctAnswers++;
localStorage.setItem('feedback',JSON.stringify(feedback[0].childNodes[0].nodeValue));
$("#feedback").append(score[0].childNodes[0].nodeValue);
$("#feedback").append("<br/>");
$("#feedback").append(feedback[0].childNodes[0].nodeValue);
}
else
{
//var val = [];
//val.push(feedback[0].childNodes[0].nodeValue);
//localstorage.setItem('feedback', JSON.stringify(val));
//localStorage.setItem('feedback',JSON.stringify(feedback[0].childNodes[0].nodeValue));
//alert(localStorage.getItem("feedback"));
/*var v={"test":feedback[0].childNodes[0].nodeValue};
localStorage.setItem('feedback',v);
alert(localStorage.getItem('feedback'));*/
scores1.push(feedback[0].childNodes[0].nodeValue);
localStorage.setItem("highscores",JSON.stringify(scores1));
var scores = localStorage.getItem("highscores");
alert(scores);
scores = JSON.parse(scores);
alert(scores[0]);
$("#feedback").html(score[1].childNodes[0].nodeValue);
$("#feedback").append("<br/>");
$("#feedback").append(feedback[0].childNodes[0].nodeValue);
$("#feedback").append("hello");
}
//$("#counter").html("left="+xPos+",top="+yPos);
$("#trFeedBack").show("slow");
display_nav(j,obj)
}
} // end function
If I understand your question, your problem is to store items with same name but related to different pages.
LocalStorage being defined by domain, and not by page, you must change the keys you use. The usual solution is to prefix the names you want.
For example :
localStorage['pages.12.feedback'] = "the feedback I'm giving related to page 12";
localStorage['global.feedback'] = "the feedback I'm giving related to the global site";
(you'll notice I use the short notation, that I find more readable that using setItem)