how to refresh php div every few seconds - javascript

So I'm basically trying to implement an online trading card game in php and (maybe minimal) javascript, and so far I have a GUI set up in php, a database with the required tables (so far) to hold the decks, fields, and other various data. I've got it to the point where i have a function that initializes the fields for both players and populates their fields and hands with cards from their deck. I also got it to the point where a player on another computer or device can take the room number of the game and join the game so the see the exact initialized field.
my next objective was to be able to set up the turn logic, and allow the screen to update for one player while the other is making plays during their turn. My problem is I'm not sure what the minimum viable solution will be for this, because I have long intricate functions that display the current field based off of values that come from a field table. So my ideal logic is set up like this:
//find game form
//host game form
//if host is set (post){
//call insert field function (a long function that creates a table for the current game being played and initializes the field and hand with random cards from the deck table)
//link game to host for future field printing
// populate host function (a function that prints a table of every card on the field with the most up to date variables to represent each spot)
}
//if find is set (post){
//call insert field function
//link game to host for future field printing
//a button form to start the game which begins by calling heads or tails
// populate find function (same as host but for find player side)
}
//if start game is set (post){
// do game logic such as coin flip which will be notified to opponent in a message field in the game table upon the refresh
}
I was wrapping the populate host function in a refreshable div like this:
print "<div><meta http-equiv='refresh' content='5' />"; //host populate just disapears
populatehost($roomnumber); //populates self and opponents in hosts perspsective
print "</div>";
so that the function would be called every 5 seconds or so, but this just causes the field to disappear after 5 seconds. So...
Why is it disappearing?
How can i get it to refresh the page and just display one instance of the field using the populate field function?
Is this approach viable? if not, what's the easiest approach I could take and how?
I also tried a solution where the function was called every 5 seconds and gotten rid of, but i'm not sure if I was doing it right, the PHP manual didn't explain it very clearly, and after lots of trial and error i think i crashed my server. It was something like this:
//loop
ob_start();
populatehost($_SESSION['gamenumber']);
sleep(5);
ob_end_clean();
I kept playing around with that logic but it either printed infinitely, didn't print at all, or crashed my server. I'm afraid to play around even more for fear of crashing the server again. Maybe someone can explain the correct way to do it or why it is not viable if it isn't?
I'm sorry if these are dumb questions, I've spent days and days researching approaches to this problem, I wasn't sure if I could implement it using javascript or ajax along with my field printing function, I tried some and they weren't working, and I'm not sure if it's because my approach is viable or not.

You can take javascript or Ajax help for div you can assign id to the div and call id in javascript:
jQuery(function () {
var $els = $('div[id^=quote]'),
i = 0,
len = $els.length;
$els.slice(1).hide();
setInterval(function () {
$els.eq(i).fadeOut(function () {
i = (i + 1) % len
$els.eq(i).fadeIn();
})
}, 2500)
})
check this fiddle:
http://jsfiddle.net/arunpjohny/asTBL/
Thanks

Related

How can I add permanent data into an variable

I'm working on a project that plays a game of rock paper scissors
the game works fine but i want to add something into it. a pointing system where it will add 1 each time a player win but i can't seem to make this work i've been trying to find workarounds for almost 2 day now but i can't seem to find any solution. The thing is the code works but after i log the function that adds 1 to a variable but after that it returns to it's original value which is 0.
const one = 1
function addone(test){
test += 1
}
addone(one)
console.log(one)
This print the original value like the function did not do anything to it. im so confused.
I see two problems in your code:
one is a const variable. That means that you can't modify its initial value.
test is a local variable inside your function, that means function won't modify the values of the variable that you pass as parameter (one).
There is an operator(++) that add a unit, I highly recommend you to use it instead of make a function:
var one = 1
one++;
console.log(one)
If you want to use a function you have to do like this:
var one = 1
function addone(test){
return test+1;
}
one = addone(one);
console.log(one)
In terms to store permanent data into a javascript variable, that's not possible. Variable are stored in RAM, that means that when you stop the program, al data of your program are wiped. Permanent store are made in database and other complex data structures.
If you want to play multiple games, you should consider to allow the players to play more games before the program finish.
thank you very much i never think that i could get more dumb so i cant manipulate it because it's just a copy of that variable that im inputing as parameter? so it means that the function did not touch the variable at all. I wish i could go back to my mother's womb.
and the const it's just a typo very sorry for this.
i did not know this website is very active i thought i would wait days just to get a response thank you very much and have a nice day

Variable checking in JSP

I am fairly new to the JSP scene, but have been programming in other languages for a few years. I am writing an application where I am passing a different variable to java based on a selection option. My main question was where to do the variable checking to see which value to pass?
Here is my current state of value checking (I am currently rewriting it in JSTL as I found sciplets are bad practice).
if (request.getParameter("Freq").equals("Minutes")) {
runOn = request.getParameter("numberOfMinutes");
} else if (request.getParameter("Freq").equals("Weekly")) {
runOn = request.getParameter("dayOfWeek");
} else if (request.getParameter("Freq").equals("Monthly")) {
runOn = request.getParameter("dayOfMonth");
} else {
runOn = "-1";
}
Should this sort of check be done on the jsp page, in javascript, or somewhere else? Looking for a best practice kind of answer.
Side question: Right now, I create a number of different drop down boxes and hide/unhide them using an onChange function in javascript. Would it be better to have one list box where the options change in javascript or keep the current system? Essentially the list boxes are asking the user what day they want their process to run. So if frequency is weekly, a list box with the days of the week would show, but if they have month selected, a list of numbers from 1 to 31 shows. It could all be done with one list box that changes its options when the 'frequency' drop down changes. Again, I'm looking for a best practice answer?
Thank you in advance!

how to implement javascript localStorage

I want to implement localStorage for one of my values in my Achievements class. So basically what this class does is take player data from backend database and if a player clears certain tasks an achievement gets unlocked. For now I have just 1 achievement defined as follows
Achievements:{ 1:{name:'First_Achievement',status:1} },
The status field acts like a flag for my achievements. If status is 1 then achievement is still locked and if it goes 0 the achievement gets unlocked.
This is a skeleton code for when my achievement gets unlocked. This block of code is checked in my game every 10 seconds to see if a certain task is cleared to unlock an achievement
checkAchievements:function(){
this.probsSolved = this.getTeamProbSolved();
if( this.Achievements[1].status == 1 && this.probsSolved.length >=3)
this.triggerAchievement(1); // spawns achievement 1 on screen
this.Achievements[1].status = 0;
},
So this works fine when I run the game. The "this.Achievements[1].status" is set to 0 until I start my game again the next time. It sets the "this.Achievements[1].status" back to 1 and the if loop runs again as status is set back to 1 which I don't want because its obvious I want my achievement to be spawned or displayed just once and not every time I run the game.
So how do go about an implement localStorage here? I suppose I need to store my "Achievements.status" field in the localStorage so that the if loop runs just once and not everytime. Or is there any other way I can implement this?
I tried the following
localStorage.setItem(this.Achievements[1].status,0);
but it does not work
any help would be appreciated! Thanks!
First, I'd recommend reading the documentation on localStorage at MDN - https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Storage. Next, let's look at your call:
localStorage.setItem(this.Achievements[1].status,0);
This says: I want you to store a value, 0, and retrieve it by the key that is the value of this.achievements[1].status.
That seems to be booleans for you. So you basically did:
localStorage.setItem(true, 0)
The localStorage API expects a string for the keyname, so it will get the string value of true which is, true. So it probably did work for you, but you used a key that probably isn't what you want. You need to think of a key name scheme that makes sense for you.

Beginner JavaScript - HTML page display no initial value display

I'm more or less new to JavaScript and am going to attempt a very basic version of Hangman to get me going.
I'm starting out with trying to display a number of lives when the user first enters the page, this will decrement with every letter they choose that doesn't feature in the word.
My JavaScript in an external file is as follows:
var lives = 5;
//Display the number of lives the user has remaining
var showLives = function(){
document.getElementById("livesLeft").innerHTML = lives;
}
//Will decrease lives each time incorrect letter is chosen
function decrementLives(){
lives--;
showLives();
}
The problem is when I initially load the HTML page, there is no value displayed for number of lives remaining, I expect it to say 5.
When I click anywhere on the body though(currently hard coded to call decrementLives() for testing purposes) it works exactly how I'd like. Displaying 4, 3, n-1 with every click.
Any ideas as to why this first isn't initially showing up like 5 like I expect. I've been thinking it might be possibly something to do with the lives variable scope?
You have to actually call the function on page load. For example in onload event:
window.onload = showLives;

Javascript table on the fly

I've got some issues with javascript. Which causes some problems.
I'm using DevExpress MVC GridView, ASP.Net MVC 3 and javascript.
This my problem:
I've got a gridview, with for example customers.
I want them to select the customers, and show them in a table generated by javascript so we dont get all those refreshes. And they can then add other information so that they can be saved again to another table, but thats not really important.
I perform some calculations before generating the table row from the selected customer. Another problem is, the devexpress gridview has an event that calls on each selection change instead of a nice ~100 ms wait so that the user can multiselect quick without triggering method 3/4 times.
Im keeping track of my own table through an array. And the GridView from DevExpress got his own events that can give me the right information, so no need to worry about that.
So I got a method receiveSelectionFields(Values){ //do something } where I receive that information from the gridview on every selection.
Then I check my array to see if they added or removed a selection, and which.
Then I call addtablerow(customer) or removetablerow(customer). Which removes the customer from my table and then from my array.
Because I make some heavy calculations in between, there is a ~60ms delay before the calculation is done (on mine computer). So if the users makes 2 selections in 60 ms. My array will have the wrong value (not being modified by the first call that adds/removes a customer) and my javascript will cause an error e.g. the table row is not deleted. I check on length of my own array and on the length of the received array to see if something has been added or removed.
So what did I try?
Making my method a recursive method, that when the problem occurs it waites 60 ms and then redo the method. But this isn't working properly.
I tried adding a global variable busy, which is true when the method is still busy. And false when it ends. But my browser just quits when doing that. This was the code:
while (true) {
setTimeout(function () {
if (busy === false) {
break;
}
}, 50);
}
But I got the feeling it just endlessly loops.
And these are all workarounds, there must be a nice way to solve this. Any thoughts?
In short:
I want a way to let the functions go off in synch. even if their being called asynch. by the user so that my array doesn't mess up.
Found the answer why my problem exists:
Since javascript is a synch. language (1 thread). the functions should've triggered at the right time. The problem is the callback from DevExpress Gridview for MVC Extensions. It makes a callback to the server, which responds in for example ~150ms with the selected field values. This will give an error if you quickly trigger the devexpress function twice. The second trigger has a window to return FASTER then the first trigger. Which would mean my coding of the table get ruined since I check if something has been added or removed. So when the first trigger (which returns after the second trigger) and my table gets updated. It shows the table prior to my last selection. Thus missing 1 row or has 1 more row then it should've.
So I got to make a function that retrieves all the events, and then place them in an order ~200 ms after each order. To make sure there is enough time for the callback to retrieve. Though this is ofcourse still not reliable, I think I will just change the requirements on this.
Your while loop condition is true, therefore the loop will just continue endlessly. You may want to try the following:
var int = setInterval(function () {
if(busy === false) {
clearInterval(int);
}
}, 50);
Try this instead of looping through the setTimeout over and over. If I had to guess, the break is breaking the if statement but not the while loop causing your browser to get stuck in an endless loop. With the above code, you can set an interval at which to run the code. In this instance, the code runs every 50ms. Once the condition inside the if statement is true, the setInterval is cleared causing the browser to continue executing its normal functionality.
Hope this helps.

Categories

Resources