var checkboxValues = JSON.parse(localStorage.getItem('checkboxValues')) || {},
$checkboxes = $("#list :checkbox");
$checkboxes.on("change", function(){
$checkboxes.each(function(){
checkboxValues[this.id] = this.checked;
});
localStorage.setItem("checkboxValues", JSON.stringify(checkboxValues));
});
I am using the code above to store the data into local storage.
{"2":false,"3":false,"4":true}
The data stored in the local storage. How can i get only the value 2 or false?
I want to collect the data in the local storage and stored into an array during submit the form.
var items=[];
$.each(checkboxValues, function(key, value) {
if(value===true){
$("#" + key).prop('checked', value);
items.push(key);
}
});
The code seem like got problem during submit which caused integrity constraint duplicate entry when store the data to database. I am using ajax to post the data to server and store the data. Is there anything wrong with my code?
Use the below code to access the checkboxValues object. You need to parse it.
var obj = JSON.parse(localStorage.getItem("checkboxValues"));
To access "2", use obj["2"].
var obj = {"2":false,"3":false,"4":true};
localStorage.setItem('checkboxValues',JSON.stringify(obj));
var storedObject = JSON.parse(localStorage.getItem('checkboxValues'));
console.log(storedObject["2"]);
Related
I have a form and I have fetch form data inside function.I want to send all
variables having data to be send to next page .Please tell me how to do it
function form_values() {
var jsvar = document.myform1.text_quest.value;
alert(jsvar); // test
$('select[name="dropdwn"]').each(function() {
alert(($(this).val()));
});
var cal = document.getElementById("otherAnswer").value;
alert(cal);
var chk = [];
$(':radio:checked').each(function() {
//alert($(this).val());
chk.push($(this).val());
});
alert(chk);
$('[type=checkbox]:checked').each(function() {
alert($(this).val())
});
} //End of function
you have to use serialize() in jquery.
For example:
url:'your_file.php?'+serialize();
This will send all the form values to that file.
For more details check here
Why not use localStorage to store the values in a json object, and use them in any of your scripts?
For example, in your form_values():
var formData = {};
$('select[name="dropdwn"]').each(function() {
formData.dropdwn = $(this).val();
});
Then on form submit:
localStorage.setItem('formData', JSON.stringify(formData));
Then from another javascript file:
var formData = JSON.parse(localStorage.getItem('formData'));
console.log(formData.dropdwn); // logs your value
Of course, make sure you check if formData exists on localStorage before trying to get a value from it.
I'm trying to use a JSON api and retrieve some data. I'm still new to it though and I can't seem to figure out which value to use. My JSON API looks something like this:
[
{"lang":"english","visual":"<span>Text</span>","weight":0.92},
{"lang":"swedish","visual":"<span>Text</span>","weight":0.22},
//etc
]
and my jQuery is:
$.getJSON(url ,function(data) {
$.each(data.lang, function(i, item) {
dataName = item["visual"];
console.log(dataName);
});
});
but nothing is being logged. How do I navigate through a JSON tree? Thanks
data.lang is undefined. lang is a property of each object in the array of objects that data holds. Simply iterate the data array, each object will contain the visual property (as well as lang);
$.getJSON(url ,function(data) {
$.each(data, function() {
var lang = this["lang"];
var dataName = this["visual"];
console.log(dataName);
});
});
I'm using jQWidgets UI framework with Knockout.js and datajs library(for supporting OData) for building client side of my app. And OData Endpoint in ASP.NET Web API2 at the server side. I created ViewModel for jqWidgets Grid as in code below:
var vm = function() {
this.items = ko.observableArray();
var self = this;
//qet data from service
OData.read(url,
function success(data, response) {
//convert data to observable array
self.items(data.results);
},
function error(err) {
alert(err.message);
});
this.removeItem = function() {
// remove item
var element = "#jqxgrid";
var cell = $(element).jqxGrid('getselectedcell');
if (cell != null && cell != "") {
var selectedrowindex = cell.rowindex;
};
var item =$(element).jqxGrid('getrowdata', selectedrowindex);
OData.request({
requestUri: url + '(' + item.CompanyID + ')',
method: "DELETE",
},
function success(data, response) {
alert('DELETE successfull');
},
function error(err) {
alert(err.message);
});
};
As you see I can get and remove items.
My problem is how to save ALL changes and send JUST changed items to server. For add/update entities at server side I have to send POST/PUT request with appropriate json object (not collection of objects). So, for example, if I want to update all changed items, i have to do PUT request for each item.
Is it any way to detect which items in observableArray was added/changed and send each of those items to server??
knockout does not do this out of the box. What I have done in the past is set an isDirty flag in the object stored in the array (this assumes your object is populated with observables, if not this wont work, and there is no easy way to do it using regular js objects). The is dirty flag watches the observable properties for changes and when on is made it sets the flag to true. Then when saves are being made you just see if the record for isDirty() == true
var entryForm = function(){
var self = this;
self.firstName = ko.observable();
self.lastName = ko.observable();
self.email = ko.observable();
self.dirty = ko.observable(false);
self.dirtyCalculations = ko.computed(function(){
//read from any observable we want to watch as part of our "dirty" calculation
self.firstName();
self.lastName();
self.email();
//if any of the above changed, this method will be called, so this model is now "dirty"
self.dirty(true);
});
//see the next section for an explanation of these lines
self.resetDirtyFlag = function(){self.dirty(false);}
self.resetDirtyFlag();
}
I see in your code above that you plug your return object straight into the array without converting the properties to observable. I would suggest converting the properties and using a similar method above.
in this example you can see a generated HTML-list. On every refresh the script requests the data-file (ajax/test.json) and builds the list again.
The generated file "ajax/test.json" is cached statically. But how can I avoid requesting this file on every refresh?
// source: jquery.com
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.
}).appendTo('body');
});
This doesn't work:
list_data = $.cookie("list_data");
if (list_data == undefined || list_data == "") {
$.getJSON('ajax/test.json', function(data) {
list_data = data;
});
}
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.
}).appendTo('body');
Thanks in advance!
How 'bout a promise ?
var list_data = localStorage.getItem("list_data"),
def = $.Deferred();
if (!list_data) {
def = $.getJSON('ajax/test.json', function(data) {
list_data = data;
localStorage.setItem("list_data", JSON.stringify(list_data));
});
}else{
list_data = JSON.parse(list_data);
def.resolve();
}
def.done(function() {
var items = [];
$.each(list_data, function(key, val) {
items.push( $('<li />', {id: key, text: val}) );
});
$('<ul/>', {'class': 'my-new-list'}).html(items).appendTo('body');
});
I'd also just use local storage, and if IE7 or below is to be supported, use the shim available on MDN!
Because your code loops through data which is not in the scope where your $.each is. Instead:
list_data = $.cookie("list_data");
function buildList(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.
}).appendTo('body');
}
//if we dont have list data
if (!list_data) {
//request for the data
$.getJSON('ajax/test.json', function(data) {
list_data = data;
//build list using new data
buildList(data);
});
} else {
//or use existing list data
buildList(list_data)
}
Note that, if you're staying on the same page, you don't need a cookie -- can just stash it in an object somewhere:
window.list_data = data;
If you need to retrieve the data later, or after the page has been refreshed, then use a cookie. But you need to serialize it, because it's not possible to store an object in a cookie:
// retrieve
list_data = $.cookie("list_data");
if (list_data) {
// have to de-serialize from string to object
list_data = JSON.parse(list_data);
} else {
// doesn't exist in cookie, make AJAX call
}
// save
$.cookie("list_data", JSON.stringify(data));
You may be able to have the browser cache the file normally, see jQuery ajax docs:
http://api.jquery.com/jQuery.ajax/
jQuery.ajax( settings )
cache
Boolean
Default: true, false for dataType 'script' and 'jsonp'
If set to false, it will force requested pages not to be cached by the browser.
Setting cache to false also appends a query string parameter, "_=[TIMESTAMP]", to the URL.
If I understand correctly, getJson is just an abstraction of an ajax call, specifically for json. You should try setting it to true, which would let the browser cache normally.
Putting it in a cookie can work as well, but has a max size of 4kb. I'm assuming your json isn't nearly that large though.
I did some research myself and it seems that it's feasible to utilize localStorage or the sessionStorage object in Modern Browsers nowadays to storage objects for a certain amount of time. Both have it's limits. Typically the localStorage and sessionStorage object have limits of 5mb. The data is persistent throughout the lifetime of the window/tab. Support isn't too bad (currently 89%) of browsers today.
Both sessionStorage and localStorage share the same API. So choosing where to store your data locally just depends on your use case.
Example of usage
if (!sessionStorage.myapp) {
var xhr = new XMLHttpRequest(),
results = {}; // Results of xhr request
// ...
// store your xhr results to sessionStorage.
// Both sessionStorage and localStorage can only store strings.
sessionStorage.setItem('myapp', JSON.stringify(results));
}
I would also avoid using cookies because of their size limits (4K) and also because cookies are passed back to the server after each transaction.
Sitepoint is a really good resource for the current existing web storage API: http://www.sitepoint.com/an-overview-of-the-web-storage-api/
The following is the code sample I have written. I would like to get the data from REST services and print it on the screen. I could get the response from REST in the JSON format. But, I could not find the way to use store it in the JSONStore and use it. Please help me to resolve this issue.
dojo.provide("index.IndexService");
dojo.require("dojo.parser");
dojo.require("dijit.Editor");
dojo.require("dijit.form.Button");
dojo.require("dijit.layout.BorderContainer");
dojo.require("dijit.layout.TabContainer");
dojo.require("dijit.layout.ContentPane");
dojo.require("dojox.data.JsonRestStore");
var xhrArgs = {
url: "http://localhost:8080/RestApp/service/customers",
handleAs: "json",
contentType : "application/json",
load: function(data){
alert(data);
},
error: function(error){
alert(error);
}
}
dojo.ready(function(){
// Create a button programmatically:
var button = new dijit.form.Button({
label: "View Transactions...",
onClick: function(){
// Do something:
dojo.byId("result1").innerHTML += "Functionality yet to be implemented! ";
}
}, "progButtonNode");
alert('hi');
var store = new dojox.data.JsonRestStore({target: "http://localhost:8080/RestApp/service/customers"});
alert(store);
store.get(1).when(function(object){
alert(object);
// use the object with the identity of 3
});
//var deferred = dojo.xhrGet(xhrArgs);
//compliantStore = new dojox.data.JsonRestStore({deferred});
alert(deferred);
});
Returned JSON value is
{"employees":{"customers":[{"city":null,"accountNo":null,"name":"Name
1","id":1},{"city":null,"accountNo":null,"name":"Name
2","id":2}],"count":2}}
How would I retrive the values?
JsonRestStore items are actually simple JavaScript objects, therefore you can always directly read properties from items. Like
var store = new dojox.data.JsonRestStore({target: "http://localhost:8080/RestApp/service/customers"});
myValue = recipeStore.getValue(item,"foo"); //stored in myValue
get = store.getValue;
set = store.setValue;
save = store.save;
// then fetch an item
var myGetValue = get(item,"foo");
var setMyValue = set(item,"foo","bar");
In synchronous mode, one can fetch without providing a callback, by directly accessing the results property from the request object that is returned from the fetch operation:
var queryResults = store.fetch({query:"?tastes='good'"}).results;
var firstItem = queryResults[0];
Did you meant something like that.. Hope it helps