I have spent a whole day on this, googling and searching for answers but still could not figure out.
My code is a bit long and it works well in Firefox but gets "Uncaught SyntaxError: Unexpected token u " from Chrome.
Can anyone points me out where I am wrong? Thanks in advance!
// when the page loads, list all the current contacts
$(document).ready(function(){
// check if localStorage database exists
if(!localStorage.getItem("customerDatabase")){
// define a JSON object to hold all current address
var contacts = {
"users":[
{
"id":"1",
"name":"dennis",
"email":"dennisboys#gmail.com"
},
{
"id":"2",
"name":"zoe",
"email":"zoeisfemale#gmail.com"
}
]
} // end of contacts JSON object
// stringify the object
var stringObject = JSON.stringify(contacts);
// store it into localStorage database
var storedDatabase = localStorage.setItem("customerDatabase", stringObject);
} else {
// list all customers upon page loads
listJSONCustomers();
}
// list all current contacts from JSON object in localStorage
function listJSONCustomers(){
var displayHTML = "";
var i;
// get the data from localStorage
var storedDatabase = localStorage.getItem("customerDatabase");
// parse the data from string to JSON object
var parseObject = JSON.parse(storedDatabase);
// access the users key of the JSON object
var userObject = parseObject.users;
// get the length of the object (how many customers the database has)
var contactsLength = userObject.length;
for(i=0; i<contactsLength; i++){
var trElement = '<tr id="address' + (i+1) + '">';
var tdId = '<td id="id' + (i+1) + '">' + userObject[i].id + '</td>';
var tdName = '<td id="name' + (i+1) + '">' + userObject[i].name + '</td>';
var tdEmail = '<td id="email' + (i+1) + '">' + userObject[i].email + '</td>';
var tdButton = '<td id="button"><button id="editButton' + userObject[i].id + '">Edit</button> | <button id="deleteButton' + userObject[i].id + '">Delete</button></td>';
displayHTML += trElement + tdId + tdName + tdEmail + tdButton + '</tr>';
}
$('#address_list').html(displayHTML);
}
// add customer to database
$('#saveCustomer').click(function(){
if( $('#customerName').val() !== "" && $('#customerEmail').val() !== "" ){
var customerName = $('#customerName').val();
var customerEmail = $('#customerEmail').val();
// get the data from localStorage
var storedDatabase = localStorage.getItem("customerDatabase");
// parse the data from string to JSON object
var parseObject = JSON.parse(storedDatabase);
// access the users key of the JSON object
var userObject = parseObject.users;
// get the new entry
var newCustomerObject = {
"id": userObject.length + 1,
"name": customerName,
"email": customerEmail
};
// push the new entry into the object
userObject.push(newCustomerObject);
// convert the object into string for localStorage
var stringObject = JSON.stringify(parseObject);
// store the JSON object into localStorage
var storedDatabase = localStorage.setItem("customerDatabase", stringObject);
// list all customes again every time a database receives a new entry
listJSONCustomers();
} else {
alert("Please enter customer's name and email.");
}
}); // end of $('#saveCustomer').click();
});
At some point, something you did corrupted the value of your LocalStorage for that key. LocalStorage can only store strings, so if you pass anything else to it, it will convert it to a string. Since your value is 'undefined', that means that at some point, you probably did something like this on accident:
var value;
localStorage.setItem('key', value);
In this case, value is undefined, which is not a string. When this gets saved, it will be converted however. Unfortunately, "undefined" is not valid JSON. That means that when it tries to parse, it will throw an exception.
To fix your issue, you should clear the bad value out with removeItem.
localStorage.removeItem("customerDatabase");
Related
I seem to have a little trouble getting a value to be returned from a dropdown lookup field. I've got the following code that gets me the values from the list I'm doing the lookup upon:
var siteUrl = _spPageContextInfo.webServerRelativeUrl;
function getDropdownValues(tempNumTitle) {
var clientContext = new SP.ClientContext(siteUrl);
var tempDropdownValueList = clientContext.get_web().get_lists().getByTitle('Temps');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View>' +
'<RowLimit>' +
'100' +
'</RowLimit>' +
'</View>');
this.tempQuery = tempDropdownValueList.getItems(camlQuery);
clientContext.load(tempQuery);
clientContext.executeQueryAsync(
// on success of getting Temp Values from dropdown
// match it with the tempNum entry
function (sender, args) {
var tempDropDownValues = {};
var tempEnumerator = tempQuery.getEnumerator();
while(tempEnumerator.moveNext()) {
var tempItem = tempEnumerator.get_current();
var tempTitle = tempItem.get_item('Title');
var tempId = tempItem.get_item('ID');
tempDropDownValues[tempTitle] = tempId;
}
selectTemp(tempNumTitle, tempDropdownValues)
},
// on failure
function (sender, args) {
console.info('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);
}
It performs this fine, giving me the dropdown values. It then calls the function selectTemp with the parameters of the tempNumTitle we are looking for, and the list of dropdown values retrieved. Here is the next function:
function selectTemp(tempNumTitle, tempValues) {
var clientContext = new SP.ClientContext(siteUrl);
var tempMatchValueList = clientContext.get_web().get_lists().getByTitle('Numbers-Temp');
var camlQuery = new SP.CamlQuery();
camlQuery.set_viewXml('<View>' +
'<Query>' +
'<Where>' +
'<Eq>' +
'<FieldRef Name="Title" />' +
'<Value Type="Text">' + tempNumTitle + '</Value>' +
'</Eq>' +
'</Where>' +
'</Query>' +
'</View>');
this.tempMatchValueQuery = tempMatchValueList.getItems(camlQuery);
clientContext.load(tempMatchValueQuery);
clientContext.executeQueryAsync(
// on success
function (sender, args) {
var temp = '';
tempEnumerator = tempMatchValueQuery.getEnumerator();
while(tempEnumerator.moveNext()) {
var tempItem = tempEnumerator.get_current();
temp = tempItem.get_item('Temp0');
}
},
// on failure
function (sender, args) {
console.info('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
);
}
It almost gets me what I'm looking for, but I get something like this:
temp: {$1E_1: 3, $2e_1: "Temp 3"}
Where I want the value of the $2e_1, or "Temp 3". How can I get that value, without just going temp["$2e_1"]?
When accessing a lookup column or a people picker column, the column value is a complex type rather than a simple string.
You can invoke .get_lookupValue() on the returned object to get a text representation of the lookup column's value, or .get_lookupId() to get the ID number of the corresponding item in the lookup list (or in the site collection's user information list in the case of a people picker column).
So in your case, assuming "Temp0" is the internal name of a lookup column, you should be able to do this:
temp = tempItem.get_item('Temp0').get_lookupValue();
I have trouble accessing object' property in the example below. On the third line I'd like to have the number 42 replaced with the value of the variable devNumTemp, but so far I'm not successfull.
What is the proper way to do this? I've tried several options, but never getting any further than getting undefined.
function getTempDev(devNumTemp, devNumHum, id, description){
$.getJSON("http://someurl.com/DeviceNum=" + devNumTemp,function(result){
var array = result.Device_Num_42.states;
function objectFindByKey(array, key, value) {
for (var i = 0; i < array.length; i++) {
if (array[i][key] === value) {
$("#id").html(description + "<div class='right'>" + array[i].value + "°C" + " (" + someVariable + "%" + ")" + "<br></div>");
}
}
};
objectFindByKey(array, 'service', 'something');
});
};
You can acces to object's properties like this
var array = result["Device_Num_" + devNumTemp].states;
It's considered a good practice to test for field's existance before trying to access it:
var array = [];
if (result && result["Device_Num_" + devNumTemp]){
array = result["Device_Num_" + devNumTemp].states;
}
This way we prevent Null Pointer Exception type errors.
I am trying to make this javascript variable with some data from an array , but i cant figure out the right syntax to make this work..
certifications will be "Win7,Win8,PDI"
var myArray = certifications.split(",");
var data = "[{" +
for (var i in myArray)
" "id":i,"text":myArray[i]}, " +
"}]";
I'm hoping to get my data variable to look something like:
var data = "[{"id":0,"text":Win7},{"id":1,"text":Win8},{"id":2,"text":PDI}]";
Try this:
var data = JSON.stringify(certifications.split(",").map(function(value, index) {
return {
id: index,
text: value
};
}));
Maybe += is what your looking for:
var certifications = "Win7,Win8,PDI";
var myArray = certifications.split(",");
var data = "[{";
for (var i in myArray) {
data += " " +
"id" +":"+i+","+
"text" + ":"+myArray[i]+"}, ";
}
data += "}]";
After following eBay's API guidelines for displaying fixed price items that fall within a specified price range, results are still showing auction based items of varying prices outside the range. I followed their tutorial word for word, so I'm not sure what I'm doing wrong.
Code:
<div id="api"></div>
<script>
function _cb_findItemsByKeywords(root)
{
var items = root.findItemsByKeywordsResponse[0].searchResult[0].item || [];
var html = [];
html.push('<table width="100%" border="0" cellspacing="0" cellpadding="3"><tbody>');
for (var i = 0; i < items.length; ++i)
{
var item = items[i];
var title = item.title;
var pic = item.galleryURL;
var viewitem = item.viewItemURL;
if (null != title && null != viewitem)
{
html.push(
'<tr id="api_microposts"><td>'
+ '<img src="' + pic + '" border="0" width="190">' + '<a href="' + viewitem + '" target="_blank">' + title +
'</a></td></tr>');
}
}
html.push('</tbody></table>');
document.getElementById("api").innerHTML = html.join("");
// Create a JavaScript array of the item filters you want to use in your request
var filterarray = [
{"name":"MaxPrice",
"value":"500",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"MinPrice",
"value":"200",
"paramName":"Currency",
"paramValue":"USD"},
{"name":"FreeShippingOnly",
"value":"true",
"paramName":"",
"paramValue":""},
{"name":"ListingType",
"value":["FixedPrice"],
"paramName":"",
"paramValue":""},
];
// Define global variable for the URL filter
var urlfilter = "";
// Generates an indexed URL snippet from the array of item filters
function buildURLArray() {
// Iterate through each filter in the array
for(var i=0; i<filterarray.length; i++) {
//Index each item filter in filterarray
var itemfilter = filterarray[i];
// Iterate through each parameter in each item filter
for(var index in itemfilter) {
// Check to see if the parameter has a value (some don't)
if (itemfilter[index] !== "") {
if (itemfilter[index] instanceof Array) {
for(var r=0; r<itemfilter[index].length; r++) {
var value = itemfilter[index][r];
urlfilter += "&itemFilter\(" + i + "\)." + index + "\(" + r + "\)=" + value ;
}
}
else {
urlfilter += "&itemFilter\(" + i + "\)." + index + "=" + itemfilter[index];
}
}
}
}
} // End buildURLArray() function
// Execute the function to build the URL filter
buildURLArray(filterarray);
url += urlfilter;
}
</script>
<!--
Use the value of your appid for the appid parameter below.
-->
<script src=http://svcs.ebay.com/services/search/FindingService/v1?SECURITY-APPNAME=*App ID*&OPERATION-NAME=findItemsByKeywords&SERVICE-VERSION=1.0.0&RESPONSE-DATA-FORMAT=JSON&callback=_cb_findItemsByKeywords&REST-PAYLOAD&keywords=iphone%205%2016gb%20unlocked&paginationInput.entriesPerPage=3>
</script>
The specifications come from this page. I would tackle this problem in two steps:
Check to see if you get the same results even if you comment out this line:
url += urlfilter;
If that happens then your problem is the way you make the request and the parameters you set are not yet relevant. If it does change then the request is going through well enough and you need to fiddle what you pass in.
In that case the parameters need some fiddling. If you are getting any results then one issue could be with the ListingType filter. The specifications say that ListingType takes a string OR can take multiple values. It might be that you want to use:
{"name":"ListingType",
"value": "FixedPrice",
"paramName":"",
"paramValue":""}
I have a problem when trying to store the results of a select query into an array with java script .
the problem is that inside the function the array is containing the right values but outside it's empty , even when i used a global var it's still empty !!!
db.transaction(function (transaction) {
var sql = "SELECT * FROM Question where idEnq=" + idEn;
transaction.executeSql(sql, undefined, function (transaction, result) {
var res = document.getElementById('results');
res.innerHTML = "<ul>";
if (result.rows.length) {
for (var i = 0; i < result.rows.length; i++) {
var row = result.rows.item(i);
ch[i] = new qu(row.id, row.text, row.type);
res.innerHTML += '<li>' + row.id + ' ' + ch[i].text + ' ' + ch[i].type + '</li>';
}
tablo = ch;
} else {
alert("No choices");
res.innerHTML += "<li> No choices </li>";
}
res.innerHTML += "</ul>";
}, onError);
}); // here the ch and the tablo array are empty
You are using asynchronous functions. Anything that wants to use the data "returned" by those functions need to be in the callback. Of course you can assign this data e.g. to a global variable, but that variable will only have the value after the callback has run (asynchronously).
you're new so have look here http://pietschsoft.com/post/2008/02/JavaScript-Function-Tips-and-Tricks.aspx
there's a part talking about calling JavaScript Function asynchronously