online data storage alternative to SQL [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I've made a very very simple quiz game in my spare time and basically the quiz poses a number of questions and when the quiz is done you get a score. I'd like for this score to be saved but I don't want to use a database to store them. Is it possible to store it in a .txt file or something like that? I have ONLY used html and JavaScript for this game (and some CSS) but I haven't used PHP and would like to avoid it at all costs.

If you are just storing the score to reuse it on the page for that user, you can store it in a cookie. This can be done with JavaScript. http://www.quirksmode.org/js/cookies.html Be aware that a user can modify the cookie to change his saved score.
If you want to store the value on the server, you will need to use some programming language on the server. There are many alternatives to PHP (e.g.: Python, Ruby, Perl).

You can use Local Storage Local Storage
to save score

I haven't used PHP and would like to avoid it at all costs.
So you want to store data in a text file but you don’t want to use PHP? How do you expect to save the data?
I would then recommend you use a pre-packaged CMS framework like WordPress. Yes it uses MySQL & PHP, but you do not have to be a PHP or MySQL expert to use it. And for what you describe, it sounds like this would be the best way for you to implement this application without learning much beyond WordPress basics.

You could use a modification of the function I used on my website, I guess. You end up storing a bunch of information in a function, and returning different results based on the calls to that function. Messy, jerry-rigged, but functional. I wouldn't recommend it for a BIG quiz game, but if you're going to use text files you're already being inefficient about it.
If you're planning on storing more than about 20 questions and answers I suggest you upgrade to a database.
function SwitchGroup(mainImage,largeFile,series)
{
document.getElementById(mainImage).src = largeFile;
document.getElementById(mainImage).rel = series;
var currdir = './glass/images/';
Anchor1 = document.getElementById('MainGallAnchorOne');
Anchor2 = document.getElementById('MainGallAnchorTwo');
Anchor3 = document.getElementById('MainGallAnchorThree');
Anchor4 = document.getElementById('MainGallAnchorFour');
Anchor5 = document.getElementById('MainGallAnchorFive');
Anchor6 = document.getElementById('MainGallAnchorSix');
if (series == 'series01')
{
// Messy, yes. But the data is all specific
Anchor1.href = currdir + 'series01/series0101big.jpg';
Anchor2.href = currdir + 'series01/series0102big.jpg';
Anchor3.href = currdir + 'series01/series0103big.jpg';
Anchor4.href = currdir + 'series01/series0104big.jpg';
Anchor5.href = currdir + 'series01/series0105big.jpg';
Anchor6.href = currdir + 'series01/series0106big.jpg';
Anchor1.title = 'Series 1';
Anchor2.title = 'Large Blue Bowl (m) (1)';
Anchor3.title = 'Blue Amphora (m)';
Anchor4.title = '14-16';
Anchor5.title = 'Aubergine Pitcher (m)';
Anchor6.title = 'Green and White and Twisty (m)';
Anchor1.rel = 'lightbox[series01]';
Anchor2.rel = 'lightbox[series01]';
Anchor3.rel = 'lightbox[series01]';
Anchor4.rel = 'lightbox[series01]';
Anchor5.rel = 'lightbox[series01]';
Anchor6.rel = 'lightbox[series01]';
}
if (series == 'series02')
{
Anchor1.href = currdir + 'series02/series0201big.jpg';
Anchor2.href = currdir + 'series02/series0202big.jpg';
Anchor3.href = currdir + 'series02/series0203big.jpg';
Anchor4.href = currdir + 'series02/series0204big.jpg';
Anchor5.href = currdir + 'series02/series0205big.jpg';
Anchor6.href = currdir + 'series02/series0206big.jpg';
Anchor1.title = 'Series 2 - Big Red and Orange Bowl (m)';
Anchor2.title = 'Crackled White and Black Bowl fading to Purple (m)';
Anchor3.title = 'Sparkly, Reduced, and odd (m)';
Anchor4.title = 'Spring Leaf (m)';
Anchor5.title = "My Sister's Christmas Present (m)";
Anchor6.title = 'Ornamental';
Anchor1.rel = 'lightbox[series02]';
Anchor2.rel = 'lightbox[series02]';
Anchor3.rel = 'lightbox[series02]';
Anchor4.rel = 'lightbox[series02]';
Anchor5.rel = 'lightbox[series02]';
Anchor6.rel = 'lightbox[series02]';
}
}

Related

Is this a reasonable class inheritance approach? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 3 years ago.
Improve this question
In trying to learn more about JavaScript (Google Apps Script flavor), I created an object structure that I think might be useful for a number of projects. My main goals for this little demonstration are:
learn the use objects (classes) and inheritance
minimize calls to the Spreadsheet Service by summoning a data table once per sheet
use the Named Ranges on the spreadsheet to access the data in the table
The code below seems successful, but surely can be improved. A couple of major questions are:
Is there a better way to accomplish the inheritance of methods and properties than this?
The Spreadsheet() function gets run for each of the Sheet objects, resulting in the environment structure having separate "ss" and "namedRangeList" properties in each of the Sheet objects. Is this normal and expected? Or is there a better approach to avoid this duplication? Or, is JavaScript just recording pointers to a single instance of these objects, so it really doesn't matter that they appear to be duplicated?
Because they are common to and the same for all of the Sheets, I had expected "ss" and "namedRangeList" to show up only at the Environment level and therefore available to the Sheets through inheritance rather than duplication.
What other changes or approaches would improve my fledgling use and understanding of classes and objects?
Here is a stripped down version of my code that preserves the essence of the structure but leaves out comments, error handling, and other functionality.
function Environment() {
this.title = 'Car & Driver';
this.ui = SpreadsheetApp.getUi();
this.dd = new Drivers();
this.cc = new Cars();
}
function Spreadsheet() {
this.ss = SpreadsheetApp.getActiveSpreadsheet();
this.namedRangeList = {};
var namedRanges = this.ss.getNamedRanges();
for (var i = 0; i < namedRanges.length; i++) {
var range = namedRanges[i].getRange();
this.namedRangeList[namedRanges[i].getName()] = {
sheet: range.getSheet().getSheetName(),
row: range.getRow(),
column: range.getColumn(),
rowCount: range.getNumRows(),
columnCount: range.getNumColumns(),
}
}
}
Spreadsheet.prototype = Object.create(Environment.prototype);
function Sheet() {
Spreadsheet.call(this);
this.sheet = this.ss.getSheetByName(this.sheetName);
this.data = this.sheet.getDataRange().getValues();
}
Sheet.prototype = Object.create(Spreadsheet.prototype);
function Cars() {
this.sheetName = 'Cars';
this.abbreviation = 'cc';
Sheet.call(this);
}
Cars.prototype = Object.create(Sheet.prototype);
function Drivers() {
this.sheetName = 'Drivers';
this.abbreviation = 'dd';
Sheet.call(this);
}
Drivers.prototype = Object.create(Sheet.prototype);
Sheet.prototype.idxOf = function(namedRange) {
return (this.namedRangeList[namedRange].rowCount == 1) ?
this.namedRangeList[namedRange].row - 1 :
this.namedRangeList[namedRange].column - 1;
}
function test_Environment() {
var env = new Environment();
env.ui.alert('The third driver is ' +
env.dd.data[3][env.dd.idxOf('ddFirst')] + ' ' + env.dd.data[3][env.dd.idxOf('ddLast')] + '.');
var tests = [
['dd', 2, 'ddLast' , 'Bailey' ],
['dd', 3, 'ddLicense' , 'pro' ],
['cc', 1, 'ccRadio' , 122.5 ],
['cc', 4, 'ccModel' , 'Corvette'],
];
tests.forEach(function(t) {
var v = env[t[0]].data[t[1]][env[t[0]].idxOf(t[2])];
Logger.log( (v == t[3]) + ': ' + (t[0] == 'dd' ? 'Driver ' : 'Car ') +
t[1] + ' ' + t[2].slice(2) + ' is ' + v );
});
env.ui.alert(env.title + ' is all done');
}
You can take a look at the mozilla page of JavaScript Objects.
Also there are a tons of questions in stack about this issue about inheritance in javascript.
Also as talked in the comments if you want someone to criticize your code take a look at Code Review

javascript multiple try catch

I read this article Multiple try-catch or one? and was wondering if there was a better way? Is there a way to just ignore the bad lines of code? My problem is I need to load multiple variables from objects that may or may not exist.
Thanks everyone
toparcv = document.getElementsByName("attribute[425]")[0].value;
toparcv = document.getElementsByName("attribute[423]")[0].value;
toparcv = document.getElementsByName("attribute[424]")[0].value;
toparcv = document.getElementsByName("attribute[426]")[0].value;
toparcv = document.getElementsByName("attribute[434]")[0].value;
bottomarcv = document.getElementsByName("attribute[271]")[0].value;
bottomarcv = document.getElementsByName("attribute[265]")[0].value;
bottomarcv = document.getElementsByName("attribute[268]")[0].value;
bottomarcv = document.getElementsByName("attribute[369]")[0].value;
bottomarcv = document.getElementsByName("attribute[433]")[0].value;
console.log(toparcv);
console.log(bottomarcv);
im trying to read a textbox from a website that randomly generates the name from about 10 different names by adding 433 or 268.
You can cover all the bottommarcv assignments like this:
[271, 265, 268, 369, 433].forEach(function(num) {
var list = document.getElementsByName("attribute[" + num + "]");
if (list && list.length) {
bottomarcv = list[0].value;
}
});
This code pre-preemptively avoids an exception by checking the integrity of variables before referencing properties on them and because it's using a loop to examine each element, it can use only one if statement for all the values.
It is a little odd to be assigning them all to the same variable. Do you really only want the last one that has a value to be used here?

covert large array of objects into smaller array objects using javascript

I have an list of values like this from a sql database.
UserName Email ComputerName DateIssued
jjsmith jjsmith#example.com JTComputer 9/14/2013
ltjoseph ltjoseph#example.com LTComputer1 10/21/2013
KTsmith KevinTem#example.com KTComputer1 01/25/2012
ltjoseph ltjoseph#example.com LTComputer2 01/11/2013
KTsmith KevinTem#example.com KTComputer2 01/25/2012
I transform my list into an array of objects.
var user_array = [
{"username":"jjsmith", "email":"jjsmith#example.com", "computerName":"JTComputer", "dateissued":"10/21/2013"}
{"username":"ltjoseph", "email":"ltjoseph#example.com", "computerName":"LTComputer1", "dateissued":"10/21/2013"}
{"username":"KTsmith", "email":"KevinTem#example.com", "computerName":"KTComputer1", "dateissued":"01/25/2012"}
{"username":"ltjoseph", "email":"ltjoseph#example.com", "computerName":"LTComputer2", "dateissued":"01/11/2013"}
{"username":"KTsmith", "email":"KevinTem#example.com", "computerName":"KTComputer2", "dateissued":"01/25/2012"}]
A function has been created by someone else that sends emails to users, it only accepts two parameters which are strings.
So I don't want to send more than 1 email per user. So I am trying to figure out how to combine the items together so that my an example set of strings look like this.
var str1 = "ltjoseph#example.com";
var str2 = "ltjoseph, LTComputer1-10/21/2013, LTComputer2-01/11/2013";
and then fire the other user function to send emails for each of the items in the list.
function sendEmails(str1, str2);
If anyone has any ideas how i can do this. Please advise..
var by_user = {};
for (var i = 0; i < user_array.length; i++) {
if (by_user[user_array[i].username]) {
// Found user, add another computer
by_user[user_array[i].username].str2 += ', ' + user_array[i].computerName + '-' + user_array[i].dateissued;
} else {
// First entry for user, create initial object
by_user[user_array[i].username] = {
str1: user_array[i].email,
str2: user_array[i].username + ', ' + user_array[i].computerName + '-' + user_array[i].dateissued
};
}
}
Now you have the by_user object, which has a single sub-object for each user, whose str1 and str2 properties are the variables you want.
by_user['ltjoseph'].str1 => ltjoseph#example.com
by_user['ltjoseph'].str2 => ltjoseph, LTComputer1-10/21/2013, LTComputer2-01/11/2013
something like this:
var str1=array[0].email
var str2=array[0].username+", "+array[0].computerName+array[0].dateissued
or use a loop and iterate through the array
I strongly recommend bringing in a library like lodash for this sort of thing and using uniq (sample here: http://jsfiddle.net/MwYtU/):
var uniqs = lodash(user_array).pluck('email').uniq().value();
If you're doing javascript and aren't acquainted with lodash or underscore, go do that because it'll save you a lot of time. Using tried and true code is a good idea. Added bonus: if you want to see how the pros are doing something like uniq you can just look at the source code.

Writing efficient hash table and hash function in JavaScript for flashcard program

I need to implement a hash table and hash function using JavaScript.
The goal is to implement a FLASHCARD program for learning French.
For now, for each item I want to store 1)English word, 2)French word 3)a phrase example in French 4) the translation from French to English.
Possibly in the future it will also be necessary to consider images and other things.
For now my idea for hash table is the following:
var words = [['être', 'to be', 'Je suis professeur d’anglais', 'I am a English Teacher'], [, , , ], ...];
I was thinking a function like this.
var flashcards = (function () {
var words = [['être','to be','Je suis professeur d’anglais','I am a English Teacher'],[,,,]];
return function (n) {
return words[n];
};
}());
alert(flashcards(0)); // 'être, ....'
Please give me your suggestions regarding this code
and, above all, a efficient way to find elements in hash table.
First of all, that has nothing to do with a hash table. It's just a 2d array :) No hashing there, and you don't need any either.
I think you'd be better off making an object for the flash card so you can access properties by name. Then just make an array of that object:
function FlashCard(){
this.e_word = this.f_word = this.e_phrase = this.f_phrase = '';
if(arguments[0])
this.e_word = arguments[0];
if(arguments[1])
this.f_word = arguments[1];
if(arguments[2])
this.e_phrase = arguments[2];
if(arguments[3])
this.f_phrase = arguments[3];
}
var flash_cards = [
new FlashCard('to be', 'être', 'I am an English Teacher', 'Je suis un professeur d’anglais'),
new FlashCard('to have', 'avoir', 'I have three brothers', 'J\'ai trois frères'),
new FlashCard('to want', 'vouloir', 'She wants to play soccer', 'Elle veut jouer au soccer')
];
function random_card(){
return flash_cards[Math.floor(Math.random()*flash_cards.length)];
}
var card = random_card();
alert(card.e_word+': '+card.f_word);
That should get you started: JSFiddle

Best practice javascript and multilanguage

what is the best practice for multilanguage website using DOM Manipulating with javascript? I build some dynamic parts of the website using javascript. My first thought was using an array with the text strings and the language code as index. Is this a good idea?
When I've built multi-lingual sites before (not very large ones, so this might not scale too well), I keep a series of "language" files:
lang.en.js
lang.it.js
lang.fr.js
Each of the files declares an object which is basically just a map from key word to language phrase:
// lang.en.js
lang = {
greeting : "Hello"
};
// lang.fr.js
lang = {
greeting : "Bonjour"
};
Dynamically load one of those files and then all you need to do is reference the key from your map:
document.onload = function() {
alert(lang.greeting);
};
There are, of course, many other ways to do this, and many ways to do this style but better: encapsulating it all into a function so that a missing phrase from your "dictionary" can be handled gracefully, or even do the whole thing using OOP, and let it manage the dynamic including of the files, it could perhaps even draw language selectors for you, etc.
var l = new Language('en');
l.get('greeting');
There are a few things you need to keep in mind when designing multilanguage support:
1 - Separate code from data (i.e. don't hard-code strings right into your functions)
2 - create a formatting hook function to deal with localization differences. Allowing formattable strings ("{0}") is better than concatenating ("Welcome to" + value), for a lot of reasons:
in some languages, a number is formatted like 1.234.678,00 instead of 1,234,567.00
pluralization is often not as simple as appending an "s" at the end of the singular
grammar rules are different and can affect the order of things so you should allow dynamic data to be appended after the translation hook: for example, "Welcome to {0}" turns into "{0} he youkoso" in japanese (this happens in pretty much every language, mind you).
3 - Make sure that you can actually format strings after the translation hook runs, so you can reuse keys.
4 - Do not, under any circunstance, hook database outputs to the translator utility. If you have multilingual data, create separate tables / rows in your database. I've seen people get this no-brainer wrong fairly often (usually for countries and states/provinces in forms).
5 - Create explicit coding practices rules for creating keys. The formatter utility function (which will look something like translate("hello world") will take a key as a parameter, and keys with slight variations make maintainance very annoying. For instance, you might end up with three keys in the following example: "enter you name", "enter your name:", "enter your name: ". Choose one format (e.g. no colon, trimmed) and catch discrepancies in code reviews. Don't do this filtering programmatically, as it can trigger false positives.
6 - Be mindful that HTML markup could potentially be needed in the translation table (e.g. if you need to bold a word in a sentence, or have footnote medical references). Test for this extensively.
7 - There are several ways of importing language strings. Ideally, you should have multiple versions of a language.lang.js file, switch between them with server side code, and reference the file from the bottom of the HTML file. Pulling the file via AJAX is also an alternative, but could introduce delays. Merging language.js into your main code file is not advisable, since you lose the benefits of file caching.
8 - Test with your target languages. This sounds silly, but I've seen a serious bug once because the programmer didn't bother to check for the existence of "é" in the key.
function Language(lang)
{
var __construct = function() {
if (eval('typeof ' + lang) == 'undefined')
{
lang = "en";
}
return;
}()
this.getStr = function(str, defaultStr) {
var retStr = eval('eval(lang).' + str);
if (typeof retStr != 'undefined')
{
return retStr;
} else {
if (typeof defaultStr != 'undefined')
{
return defaultStr;
} else {
return eval('en.' + str);
}
}
}
}
After adding this to your page, you can work with it like this:
var en = {
SelPlace:"Select this place?",
Save:"Saved."
};
var tr = {
SelPlace:"Burayı seçmek istiyor musunuz?"
};
var translator = new Language("en");
alert(translator.getStr("SelPlace")); // result: Select this place?
alert(translator.getStr("Save")); // result: Saved.
alert(translator.getStr("DFKASFASDFJK", "Default string for non-existent string")); // result: Default string for non-existent string
var translator = new Language("tr");
alert(translator.getStr("SelPlace")); // result: Burayı seçmek istiyor musunuz?
alert(translator.getStr("Save")); // result: Saved. (because it doesn't exist in this language, borrowed from english as default)
alert(translator.getStr("DFKASFASDFJK", "Default string for non-existent string")); // result: Default string for non-existent string
If you call the class with a language that you haven't defined, English(en) will be selected.
Just found a nice article about i18n in javascript:
http://24ways.org/2007/javascript-internationalisation
Although a simple google search with i18n + javascript reveals plenty of alternatives.
In the end, it depends on how deep you want it to be. For a couple of languages, a single file is enough.
You could use a framework like Jquery, use a span to identify the text (with a class) and then use the id of each span to find the corresponding text in the chosen language.
1 Line of Jquery, done.
After reading the great answers by nickf and Leo, I created the following CommonJS style language.js to manage all my strings (and optionally, Mustache to format them):
var Mustache = require('mustache');
var LANGUAGE = {
general: {
welcome: "Welcome {{name}}!"
}
};
function _get_string(key) {
var parts = key.split('.');
var result = LANGUAGE, i;
for (i = 0; i < parts.length; ++i) {
result = result[parts[i]];
}
return result;
}
module.exports = function(key, params) {
var str = _get_string(key);
if (!params || _.isEmpty(params)) {
return str;
}
return Mustache.render(str, params);
};
And this is how I get a string:
var L = require('language');
var the_string = L('general.welcome', {name='Joe'});
This way you can use one js code for multi language by multi word :
var strings = new Object();
if(navigator.browserLanguage){
lang = navigator.browserLanguage;
}else{
lang = navigator.language;
}
lang = lang.substr(0,2).toLowerCase();
if(lang=='fa'){/////////////////////////////Persian////////////////////////////////////////////////////
strings["Contents"] = "فهرست";
strings["Index"] = "شاخص";
strings["Search"] = "جستجو";
strings["Bookmark"] = "ذخیره";
strings["Loading the data for search..."] = "در حال جسنجوی متن...";
strings["Type in the word(s) to search for:"] = "لغت مد نظر خود را اینجا تایپ کنید:";
strings["Search title only"] = "جستجو بر اساس عنوان";
strings["Search previous results"] = "جستجو در نتایج قبلی";
strings["Display"] = "نمایش";
strings["No topics found!"] = "موردی یافت نشد!";
strings["Type in the keyword to find:"] = "کلیدواژه برای یافتن تایپ کنید";
strings["Show all"] = "نمایش همه";
strings["Hide all"] = "پنهان کردن";
strings["Previous"] = "قبلی";
strings["Next"] = "بعدی";
strings["Loading table of contents..."] = "در حال بارگزاری جدول فهرست...";
strings["Topics:"] = "عنوان ها";
strings["Current topic:"] = "عنوان جاری:";
strings["Remove"] = "پاک کردن";
strings["Add"] = "افزودن";
}else{//////////////////////////////////////English///////////////////////////////////////////////////
strings["Contents"] = "Contents";
strings["Index"] = "Index";
strings["Search"] = "Search";
strings["Bookmark"] = "Bookmark";
strings["Loading the data for search..."] = "Loading the data for search...";
strings["Type in the word(s) to search for:"] = "Type in the word(s) to search for:";
strings["Search title only"] = "Search title only";
strings["Search previous results"] = "Search previous results";
strings["Display"] = "Display";
strings["No topics found!"] = "No topics found!";
strings["Type in the keyword to find:"] = "Type in the keyword to find:";
strings["Show all"] = "Show all";
strings["Hide all"] = "Hide all";
strings["Previous"] = "Previous";
strings["Next"] = "Next";
strings["Loading table of contents..."] = "Loading table of contents...";
strings["Topics:"] = "Topics:";
strings["Current topic:"] = "Current topic:";
strings["Remove"] = "Remove";
strings["Add"] = "Add";
}
you can add another lang in this code and set objects on your html code.
I used Persian For Farsi language and English, you can use any type language just create copy of this part of code by If-Else statement.
You should look into what has been done in classic JS components - take things like Dojo, Ext, FCKEditor, TinyMCE, etc. You'll find lots of good ideas.
Usually it ends up being some kind of attributes you set on tags, and then you replace the content of the tag with the translation found in your translation file, based on the value of the attribute.
One thing to keep in mind, is the evolution of the language set (when your code evolves, will you need to retranslate the whole thing or not). We keep the translations in PO Files (Gnu Gettext), and we have a script that transforms the PO File into ready to use JS Files.
In addition:
Always use UTF-8 - this sounds silly, but if you are not in utf-8 from start (HTML head + JS encoding), you'll be bust quickly.
Use the english string as a key to your translations - this way you won't end up with things like: lang.Greeting = 'Hello world' - but lang['Hello world'] = 'Hello world';
You can use a google translator:
<div id="google_translate_element" style = "float: left; margin-left: 10px;"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.HORIZONTAL}, 'google_translate_element');
}
</script>
<script type="text/javascript" src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
</div><input type = "text" style = "display: inline; margin-left: 8%;" class = "sear" placeholder = "Search people..."><button class = "bar">🔎</button>
class Language {
constructor(lang) {
var __construct = function (){
if (eval('typeof ' + lang) == 'undefined'){
lang = "en";
}
return;
};
this.getStr = function (str){
var retStr = eval('eval(lang).' + str);
if (typeof retStr != 'undefined'){
return retStr;
} else {
return str;
}
};
}
}
var en = {
Save:"Saved."
};
var fa = {
Save:"ذخیره"
};
var translator = new Language("fa");
console.log(translator.getStr("Save"));
For Spring bundles and JavaScript there are simple solution: generate i18n array in template (e.g. JSP) and use it in JavaScript:
JSP:
<html>
<script type="text/javascript">
var i18n = [];
<c:forEach var='key' items='<%=new String[]{"common.deleted","common.saved","common.enabled","common.disabled","...}%>'>
i18n['${key}'] = '<spring:message code="${key}"/>';
</c:forEach>
</script>
</html>
And in JS:
alert(i18n["common.deleted"]);
See also Resolving spring:messages in javascript for i18n internationalization

Categories

Resources