Permanent change to DIV after data has been saved to DB [closed] - javascript

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 6 years ago.
Improve this question
How do I make this permanent and global?
By this I mean the color change of the div!
The data has been stored to DB and the div must remain red for all times for all computers ha-ha and not until the page reloads! How can this be achieved?
var x = document.getElementById("mySelect1").selectedIndex;
var y = document.getElementById("mySelect2").selectedIndex;
var color = "#ff0000";
request.done(function (data) {
if (data != -1) {
if (x==0 && y==0) {
document.getElementById("A9").style.backgroundColor = color;
}
alert("You Have successfully made an appointment");
location.assign("AjanvarausPage.html");
}

Server-side code will be needed to keep track of the change and notify all clients. The former will require some form of persistence, global memory/cache or database perhaps, while the latter is the trickier part. Since a server generally doesn't know if a web client is connected or not it has to be told there is a client needing to be notified.
But there are a number of ways this could be done.
Polling
Each client must poll the server-side code for potential changes. There are in general two different types of polling, short and long.
Short Polling
each client will need to ask the server if there are changes in a loop, usually with a delay to prevent hammering the server. The server responds immediately notifying the client if there are changes or not.
Long Polling
similar to short polling, with the single exception of the server not responding unless there are changes. This keeps the request open until it is either satisfied (there are changes to report) or it times out.
Push Notification
There are technologies, such as SignalR, that has the client register with the server and can then be notified repeatedly without further notification.

Related

What is the purpose of the JWT and Middleware function in Nodejs? [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 10 months ago.
Improve this question
Every time a protected url is called i check for req.user that is set up automatically by the JWT middleware.
Now I'm wondering:
1 - where does JWT tokens are stored when calling sign() ?
2 - do i have to verify() the token every time a protected url is called? if yes why?
3 - When i set a new token for an already signed user does the old token (if exists) gets deleted ? What if the expiration is not been set up or is 5 years for example?
4 - Why can't I set new tokens on same browser/app page ? I get invalid signature error if i register a new token but the token matches (i checked) It's like I can't signin more than 1 user on same browserstrong text
JWT tokens do not need to be stored anywhere really, although some might do
you protect routes for a given reason, therefore it is essential to verify that non-authorised requests do not go through.
this depends on how you engineered the auth system, normally all the JWT tokens upon generation need to be told when to expire
I do not quite understand the problem here, you need to offer us more details before expecting a solution

Save a variable [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 7 years ago.
Improve this question
I have the variable: var balance = 50;
I am wondering if there is a way to save the balance variable, so that it maintains its amount when a user enters the webpage again.
What should I do? Can I do it with a cookie, do I need to put it in my MSSQL database?
And if I can set it with a cookie how should i do it than?
Or can it be done with a jquery/javascript script, that can save the date.
You can use localStorage
var balance = 50;
localStorage.setItem("balance", balance); // Sets 50 in local storage
localStorage.getItem("balance"); // Returns 50
Limitation - It will not work if user visits page in other browser/device.
You can use localStorage.
var balance = localStorage.getItem('balance');
if (balance === null) {
// Not found, set value from database or wherever you get the value
balance = 50; // Or whatever value
} else {
balance = +balance; // Convert the retrieved value to a number, since localStorage stores everything as string.
}
// After manipulating the balance, etc...
newBalance = balance - 20; // Assuming the user just used up 30 credits
localStorage.setItem('balance', newBalance);
You have to be careful however, as not to depend on this value from a security standpoint, as the user can modify it.
What you're talking about is the concept of persistence. You can achieve this in a number of ways, but they all rely on saving a little piece of data on the clients computer.
1. Use sessions
Most common way to remember a user is to create a session for him on your server. Within this session you can save all kinds of data, for instance a balance. To get this data from your javascript to your session you can send a post request to your server containing the information of the clients balance. The server remembers which user he's handling by the means of a session cookie on the clients computer (contains a unique ID per session).
2. Only use cookies
With javascript you can very easily set cookies doing this: document.cookie = "balance=50". Obviously you'll replace the '50' with whatever value the clients balance actually is. Next time the user visits your page, you can read the cookie again using var cookie = document.cookie. This works even between browser instances.
3. Use a database
If you have the means to identify a user (e.g. he logged in to your website, or by the means of a session) you can just save whatever data you want into a database. Key is to recognize which user you're dealing with.
I like to use sessions when I'm creating a website. I like to keep most of the responsibilities on my server so that I only have to worry about what is displayed on the pages, and not about manipulating data and whatnot. I recommend you using sessions and posting the users balance whenever you want to save it.

Using rails how to synchronize variable in controller to the view where the controller is the initiator of the update [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
I tried the long polling in AJAX, where the client calls the server requesting data at a certain interval. - The updating of list in UI was initiated by the client
Below are the code:
server_controller.rb
##x=0
def results
##x++
render :json => ##x
end
index.html.erb
<button id='get_value' class="btn">Run</button>
<ul id="value_variable_from_controller"><ul>
$(document).ready(function() {
var getPoll=function getValue(trigger) {
$.ajax({
type: 'GET',
url: '/server/results/',
success: function(data, status) {
if (data < 50){
$('#value_variable_from_controller').append("<li>"+data+"</li>");
setTimeout(getValue(true), 1000);}},})}
$(document).on("click","#get_value",getPoll);
The Question is how can i do it oppositely where the controller has the power to initiate/send the data and the list on HTML was synchronously updating/appending?
This is more tricky to do, because you need an additional technology. HTTP and its request-respond model can't do this. A client (browser) can't receive requests from a server.
You'll end up with a bidirectional communication, because first the client ask the server things and later the server asks the client to update. A technology for doing this is websockets. Rails don't include this, so you need to add it via gems (websockets-gem) or/and probably an event driven, non-blocking server like node.js is useful as well.
There are different tutorials out there, which give you a start. Here is one example with two nice little graphics, which explain the situation.

Server-side validation to prevent illegal POST requests [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 8 years ago.
Improve this question
For my webapp (angular + node.js), I'm implementing a gamification system where users gain points for performing actions like answering questions, watching a video, etc. Currently, I simply post to '/api/users/updatepoints' with the user's id and number of points changed to update the database.
This is of course not secure, since a user could easily do an ajax request from the console while logged in, and I was wondering how I can prevent users from illegally sending out ajax requests? What sort of server-side validation could I use to do so?
//front end
$http.post('/api/users/updatepoints', {
kidId: xxx,
pointsChanged: yyy
})
//backend
exports.updatePoints = function(req, res) {
var kidId = req.body.kidId,
pointsChanged = req.body.pointsChanged;
User.findOne({_id: kidId}, function(err, user) {
if (err) return res.send(400);
user.points += pointsChanged;
user.save(function(err) {
if (err) return res.send(400);
return res.send(200)
});
})
}
The simple answer is "you can't".
A sufficiently determined hacker will always be able to take control of anything you are running on their computer. The only way to avoid that is to validate everything server side.
For example the only way to defeat "map hacks" in competitive online play is to never send information to the client unless that information is being displayed to the user.
If it's important, do it server side. Let the client side do its processing and validate and verify everything it sends you.
This is much too big a subject to properly discuss in a format like this though. Try doing some internet searches on preventing client hacks in games.

Limit time user is allowed on website before forcing a login [closed]

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'm not sure what language to use (php, Java or other) but I'll need to limit the amount of time a user is allowed to browse our website before forcing a login popup appears.
Example:
Unregistered user browsing our website, after 1mins of browsing we show a popup saying they need to log on to continue browsing.
If anyone has a better way of doing this I'd be happy to adapt.
Apologies for being extremely vague.
as JustinM151 or Mörre and others allready pointed out you may be informed that all implementations are "not safe" for bypassing this task.
you can use sessions for this like
session_start();
$expire_seconds = 60; // expire in 60 seconds
if( ! isset( $_SESSION['visit_expire'] ) {
$_SESSION['visit_expire'] = time() + $expire_seconds;
}
if( !$isLoggedIn && $_SESSION['visit_expire'] > time() ) {
// force login
// display whatever
}
You will want to do this in Javascript to have it stop themin their tracks, however, if you want to restrict further browsing after the time limit, you can use PHP/SESSION variables to stop them from moving on to new pages.
When they first access your site set a session variable with the time.
session_start();
$_SESSION['browseTime'] = date('U'); //Seconds since Unix Epoch
then on every page load check their browse time compared to current time...
if(!empty($_SESSION['browseTime'])) {
if(date('U') - $_SESSION['browseTime'] > $secondsAllowed) {
header('location: login.php?timesup=y');
}
}
granted they can easily bypass this method or the javascript method by clearing their cookies.
A way to do this that is harder to bypass is to store their times in a database table tied to their IP address. but that too can be bypassed.

Categories