var nicWinsVsMac;
if (tempresult === win) {
wincount = JSON.parse(localStorage.getItem (playerName + 'wincount'));
wincount += 1;
localStorage.setItem(playerName + 'wincount', wincount);
winsvsopponent = 'WinsVs' + opponent;
winsvsopponent = JSON.parse(localStorage.getItem(playerName + 'WinsVs' + opponent));
winsvsopponent += 1;
console.log(winsvsopponent);
localStorage.setItem(playerName + 'WinsVs' + opponent, 'winsVs' + opponent);
console.log(localStorage.getItem(nicWinsVsMac));
}
playerName and opponent are parameters passed in. In this case, playerName = 'nic' and opponent = "Mac"
My browser is giving me "unexpected token w" on the line where i parse out the localStorage. I cannot figure out what is going on. Any help would be great. Thanks!
Instead of using a separate localStorage variable for each attribute of the player. Why not store all the players attributes in a single object and then save that to localStorage.
For example, you can do the following:
var player = new Object();
player.name = 'Mac';
player.winCount = 3;
player.winAgainst = new Array();
localStorage.setItem(player.name, JSON.stringify(player));
var player1 = JSON.parse(localStorage.getItem(player.name));
console.log(player1.name + " has " + player1.winCount + " wins.");
This allows you to save all the player's attributes to a single localStorage variable making it much easier to read and write from.
In regards to the error you are recieving, I believe the issue with your code is that you are not using JSON.stringify in the call to setItem.
Related
Hi i'm currently trying to do a function that will get a key(string)/value(JSON) pair from a dictionary stored at a database and add information about the player into a temporary JSON(playersInfo), then set that JSON object back to the value which i got earlier, i'm still very noob at javascript and i couldn't find the right syntax to do it.
If there's anything i can do to make myself clear please let me know.
Both Get...Data() functions return different dictionaries.
handlers.UpdateJackpotPlayers = function(args, context) {
var playersInfo = {};
var userData = server.GetUserData({
PlayFabId: currentPlayerId
});
var serverData = server.GetTitleInternalData();
playersInfo = JSON.parse(serverData.Data["jackpotPlayers"].Value);
playersInfo.PlayerId += JSON.parse(" / " + currentPlayerId);
playersInfo.PlayerName += JSON.parse(" / " +
userData.Data["PlayerName"].Value);
playersInfo.AchievedJackpot += JSON.parse(" / " + args);
server.SetTitleInternalData({
"Key": "jackpotPlayers",
"Value": JSON.stringify(playersInfo)
});
}
I am trying to perform a simple addition on data I have gathered from an external source via JSON. The data I am getting is being returned as a string but is a number so I have tried using both parseInt() and Number() to no avail. I have shown a simple section of the code below:
var total_energy = 0;
var energy_val;
$.each(result.report.food.nutrients, function (i, v) {
if (v.name == "Energy"){
energy_val = v.value;
var energy = Number(energy_val);
total_energy = total_energy + energy;
console.log("energy " + energy);
console.log("totalenergy " + total_energy);
energy_val = "";
energy = 0;
}
}
The console returns the correct value for energy each time but the totalenergy value just seems to stay the same as the energy value. The sum doesn't seem to have any affect. Could anyone tell me where I am going wrong with this problem?
change console.log("energy " + total_energy); to console.log("energy " + energy);
try parseInt your values... can be this
I doubt if its due to the closure created in the loop where you are iterating over the items. Try the following code.
var total_energy = 0;
var energy_val;
$.each(result.report.food.nutrients, function (i, v) {
var item = v;
//Calling calculateEnergy() function so that each 'item' is the current instance 'v' value.
(function calculateEnergy(itemClicked))(item);
}
function calculateEnergy(itemClicked){
if(itemClicked.name == "Energy"){
energy_val = itemClicked.value;
var energy = Number(energy_val);
total_energy = total_energy + energy;
console.log("energy " + energy);
console.log("totalenergy " + total_energy);
energy_val = "";
energy = 0;
}
}
I have put comments within the code.
Update console.log() is buggy with ajax requests. So instead of logging, try creating an html div and populate the values there.
is there anyway that I can change the output from
Name: =daniel to Name: Daniel for all of the followings?
Picture in this URL > http://imgur.com/dgOMjhy
<h2>Your details have been submitted!</h2>
<h2>You have entered the following data: </h2>
<script type="text/javascript">
var formData = location.search;
formData = formData.substring(1, formData.length);
while (formData.indexOf("+") != -1) {
formData = formData.replace("+", " ");
}
formData = unescape(formData);
var formArray = formData.split("&");
document.write("<p>");
for (var i = 0; i < formArray.length; ++i) {
document.writeln(formArray[i] + "<br />");
}
document.write("</p>");
</script>
Sure, but this won't get you very far.
Change this line:
document.writeln(formArray[i] + "<br />");
to
document.writeln(formArray[i].replace("=", ": ") + "<br />");
But if I were you I would work on parsing the data into an actually usable object for further manipulation, currently you only work by doing String manipulations on the page URL.
Edit: To expand on the question you posted in the comment to this post:
To begin, you should try to move away from moving data via URL or GET requests, as these are quite visible, restrictive in encoding, prone to manipulation and recording. Especially data like credit card information should not be embedded in URLs.
Anyhow, in regard to parsing let's start with splitting your formArray further and storing the key-value pairs in an object:
var formArray = formData.split("&");
var formDataObj = {}; //in this we will store the data
//let's assume here that you have no key duplicates in your data
//and that it is always properly formatted
formArray.forEach(function (item) {
var key = item.split("=")[0];
var value = item.split("=")[1];
formDataObj[key] = value;
});
//if you processed your data like this you can then access it more precisely like so
document.writeln("<p>Customer " + formDataObj.customerNumber + " has card number " + formDataObj.cardNumber + "</p>");
I think it's obvious how this can be advantageous.
you can use a helper function
function capitalize(a)
{
return a[0].toUpperCase() + a.slice(1);
}
I'm trying to get the value of a hidden input from a form in my HTML, using javascript.
But after trying several different ways to get the value, it always says in console(firebug) that the variable is null.. heres the javascript:
var mcq_test = form.mcq_test.value;
console.log("mcqid=" + mcq_test)
var mcq_num_questions = form.mcq_num_questions.value;
console.log("totalquestions=" + mcq_num_questions)
var x = 1;
var send = [];
send.push("mcq_test=");
send.push(mcq_test);
console.log("Send: " + send);
// have commented out the bits below...just go through them carefully looking at the string functions, put them in the send += (SRING 1 + STRING 2 + ...) format
for (var x = 1; x <= mcq_num_questions; x++) {
var questionidd = "mcq_question_id";
console.log("1 = " + questionidd);
var questionid = questionidd.concat(x); // mcq_question_id$ctr the question numer
console.log("2 = " + questionid);
var mcqid = form.questionid.value; // the questions id on db
console.log("3 = " + mcqid);
var answerr = "mcq_question";
var answer = answerr.concat(x); // mcq_question$ctr the questions chosen answer
var chosenanswer = form.answer.value; // the answers value
console.log("4 = " + chosenanswer);
var amp = "&";
var equal = "=";
var questionide = questionid.concat(equal); // "mcq_question_id$ctr="
var questionida = amp.concat(questionide); // "&mcq_question_id$ctr="
var answere = amp.concat(answer,equal); // "&mcq_question$ctr="
if (x = 1) { send.push(questionide, mcqid, answere, chosenanswer); }
else {
send.push(questionida, mcqid, answere, chosenanswer);
}
}
Console:
[04:08:00.328] TypeError: questionID is null
[04:08:00.327] My new function
[04:08:00.327] mcqid=566
[04:08:00.327] totalquestions=3
[04:08:00.327] Send: mcq_test=,566
[04:08:00.328] 1 = mcq_question_id
[04:08:00.328] 2 = mcq_question_id1
Form:
echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"$questionID\" form=\"SubmitTest\" />";
-- Update
Answer found! Turns out, you can't use the syntax document.getElementByID() or form.variable.value; and put a variable in there, it has to be a string or written like this:
form[variable].value;
I didn't find an equivalent for getElementById but the form method works for me.
You need to make sure that the DOM has loaded before you try accessing it. Put the Javascript after the HTML or setup an event to trigger the variable definition.
when using this
echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"$questionID\" form=\"SubmitTest\" />";
here before going to create input type make sure your '$questionID' is not null
use this then test
echo"<input type=\"hidden\" name=\"mcq_question_id$ctr\" id=\"mcq_question_id$ctr\" value=\"questions\" form=\"SubmitTest\" />";
I am working on a Browser-based media player which is written almost entirely in HTML 5 and JavaScript. The backend is written in PHP but it has one function which is to fill the playlist on the initial load. And the rest is all JS. There is a search bar that refines the playlist. I want it to refine as the person is typing, like most media players do. The only problem with this is that it is very slow and laggy as there are about 1000 songs in the whole program and there is likely to be more as time goes on.
The original playlist load is an ajax call to a PHP page that returns the results as JSON. Each item has 4 attirbutes:
artist
album
file
url
I then loop through each object and add it to an array called playlist. At the end of the looping a copy of playlist is created, backup. This is so that I can refine the playlist variable when people refine their search, but still repopulated it from backup without making another server request.
The method refine() is called when the user types a key into the searchbox. It flushes playlist and searches through each property (not including url) of each object in the backup array for a match in the string. If there is a match in any of the properties, it appends the information to a table that displays the playlist, and adds it to the object to playlist for access by the actual player.
Code for the refine() method:
function refine() {
$('#loadinggif').show();
$('#library').html("<table id='libtable'><tr><th>Artist</th><th>Album</th><th>File</th><th> </th></tr></table>");
playlist = [];
for (var j = 0; j < backup.length; j++) {
var sfile = new String(backup[j].file);
var salbum = new String(backup[j].album);
var sartist = new String(backup[j].artist);
if (sfile.toLowerCase().search($('#search').val().toLowerCase()) !== -1 || salbum.toLowerCase().search($('#search').val().toLowerCase()) !== -1 || sartist.toLowerCase().search($('#search').val().toLowerCase()) !== -1) {
playlist.push(backup[j]);
num = playlist.length-1;
$("<tr></tr>").html("<td>" + num + "</td><td>" + sartist + "</td><td>" + salbum + "</td><td>" + sfile + "</td><td><a href='#' onclick='setplay(" + num +");'>Play</a></td>").appendTo('#libtable');
}
}
$('#loadinggif').hide();
}
As I said before, for the first couple of letters typed, this is very slow and laggy. I am looking for ways to refine this to make it much faster and more smooth.
$('#search') isn't cheap. Move it outside the loop.
Move append() outside the loop. Just accumulate the markup in a string and append it once after the loop.
This should be much faster
function refine() {
$('#loadinggif').show();
$('#library').html("<table id='libtable'><tr><th>Artist</th><th>Album</th><th>File</th><th> </th></tr></table>");
playlist = [];
var srchText = $('#search').val().toLowerCase();
var markup = ["<tbody>"];
for (var j = 0; j < backup.length; j++) {
var sfile = backup[j].file.toLowerCase();
var salbum = backup[j].album.toLowerCase();
var sartist = backup[j].artist.toLowerCase();
if (sfile.search(srchText) !== -1 || salbum.search(srchText) !== -1 || sartist.search(srchText) !== -1) {
playlist.push(backup[j]);
num = playlist.length-1;
markup.push("<tr><td>" + num + "</td><td>" + sartist + "</td><td>" + salbum + "</td><td>" + sfile + "</td><td><a href='#' onclick='setplay(" + num +");'>Play</a></td></tr>");
}
}
markup.push("</tbody>");
$("#libtable").append(markup.join(''));
$('#loadinggif').hide();
}
I would suggest building your playlist information a little differently. You could probably get a pretty decent performance gain just by splitting up your playlist info by first letter.
albums = {
'a': [list of albums starting with a],
'b': ...
}
And doing the same for files and artists, of course.
One thing you could do is to take advantage of jQuery's ability to cache document fragments (the example is from a talk John Resig gave but you could apply it to your code):
// SLOW AS IT IS NOT CACHED. BECAUSE OF FOO
$("ul").append("<li><a>" + foo + "</a></li>");
// FAST. DOCUMENT FRAGMENT IS CACHED
$("<li><a></a></li>")
.find("a").text(foo).end()
.appendTo("ul");
This would be applicable to your line above:
$("<tr></tr>").html("<td>" + num + "</td><td>" + sartist + "</td><td>" + salbum + "</td><td>" + sfile + "</td><td><a href='#' onclick='setplay(" + num +");'>Play</a></td>").appendTo('#libtable');