JavaScript Rating after refreshpage - javascript

I have a java script functions to display rating..
When user click on stars to rate I need to display the Thank you for rating message and when user refresh the page I need to display thank you for rating message instead of Rate this article.
Below is my code: could any one help me out?
<script type="text/javascript">
var sMax; // Isthe maximum number of stars
var holder; // Is the holding pattern for clicked state
var preSet; // Is the PreSet value onces a selection has been made
var rated;
// Rollover for image Stars //
function rating(num){
sMax = 0; // Isthe maximum number of stars
for(n=0; n<num.parentNode.childNodes.length; n++){
if(num.parentNode.childNodes[n].nodeName == "A"){
sMax++;
}
}
if(!rated){
s = num.id.replace("_", ''); // Get the selected star
a = 0;
for(i=1; i<=sMax; i++){
if(i<=s){
document.getElementById("_"+i).className = "on";
document.getElementById("rateStatus").innerHTML = num.title;
holder = a+1;
a++;
}else{
document.getElementById("_"+i).className = "";
}
}
}
}
// For when you roll out of the the whole thing //
function off(me){
if(!rated){
if(!preSet){
for(i=1; i<=sMax; i++){
document.getElementById("_"+i).className = "";
document.getElementById("rateStatus").innerHTML = me.parentNode.title;
}
}else{
rating(preSet);
document.getElementById("rateStatus").innerHTML = document.getElementById("ratingSaved").innerHTML;
}
}
}
// When you actually rate something //
function rateIt(me){
if(!rated){
document.getElementById("rateStatus").innerHTML = document.getElementById("ratingSaved").innerHTML + " :: "+me.title;
preSet = me;
rated=1;
sendRate(me);
rating(me);
}
}
// Send the rating information somewhere using Ajax or something like that.
function sendRate(sel){
alert("Your rating was: "+sel.title);
}
</script>
<form id="form1">
<span id="rateStatus">Rate This Article:</span>
<span id="ratingSaved">Thank you for rating.</span>
<div id="rateMe" title="Rate Me...">
<a onclick="rateIt(this)" id="_1" title="ehh..." onmouseover="rating(this)" onmouseout="off(this)"></a>
<a onclick="rateIt(this)" id="_2" title="Not Bad" onmouseover="rating(this)" onmouseout="off(this)"></a>
<a onclick="rateIt(this)" id="_3" title="Pretty Good" onmouseover="rating(this)" onmouseout="off(this)"></a>
</div>

you need to save the cookie as soon as user rate the article and check that cookie value when you load the page again to confirm if the article is already loaded or not.

Or you can also fetch the current ratings of this article from the server if you are refreshing the page anyways

You have a few options here, and what you do is going to depend on your requirements.
The big issue is one of permanence. By that, if I rate something and get the Thank You message should I see that if I look at the same page from my phone browser, or a browser on another computer? Otherwise, is it simply a message that needs to show once and you don't care if I see the "Please rate" option again later?
Based on your question about saving state between page refreshes, it sounds like your needs are more on the side of saving permanence.
Ultimately, the only way to guarantee that the rating state is saved permanently is to tie it into a user account on the backend (server) application. That way, when I view the same page from other browsers, or after a long time, then the server can lookup in the database and see that "Geuis rated this, show the Thank You message".
If you only need to show the Thank You for a short amount of time, you can store a key in a temporary cache like memcache. On each page refresh, a short piece of javascript can make an xhr request to your cache server to check if I've rated the page or not. Eventually the key falls out of the cache, so maybe in an hour or a day when I go back to see the page then I'll be prompted to rate the page. This is a semi-permanent solution, but it does work across any device or browser as long as its tied into an account.
The most fragile, but easiest, solution to implement is purely client-side. Here, your options are to either a) store the rated/not rated value in a cookie, or b) use localStorage. In either situation, it will let store the state. But cookies and localStorage are not transferred between devices or browsers. localStorage won't expire, but eventually cookies will. Also, the user can eventually decide to clear out their cookies and localStorage caches and would set the state back to "Rate me".
I'm not providing any code samples because, as I hope you can see, the answer really lies first in exactly what you're trying to accomplish along the spectrum of permanence.
And just to say it, there's really no such thing as anonymous permanence. I.e. you can't have a user to be anonymous to your site yet save their voting state permanently in a way that transfers between browsers. You have to have something akin to a server-side account to do that.

Related

How to create global constant or variable whose value dont get reset after closing the app in reactjs [duplicate]

I'm trying to make a page on my tumblr that has a button on it, which counts how many times it's been pressed. I've gotten it to work, but a browser close or refresh clears the value, and clicks from different people don't stack. Here's what I have:
<body>
<div class="main">
<h3>Click Counter</h3>
<button id="clickme">Click me: 0</button>
<h5>Filler Text</h5>
</div>
<script>
var button = document.getElementById("clickme"),
count = 0;
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
};
</script>
</body>
This makes the button count up when pressed, but I want it to behave like so:
User #1 clicks twice. Counter reads two.
User #2 visits the page, counter is already at two, user clicks 3 times. Counter is at 5.
User #3 visits, counter is still at 5 for them as well, etc.
As of right now, each user visits the page and the value starts at zero. Help?
Depending on your needs, you could use localStorage.
count = localStorage.getItem('count');
count = parseInt(count); // because localstorage stores everything in strings
// First time the value does not exist...
if(count == null) {
count = 0;
}
button.onclick = function() {
count += 1;
button.innerHTML = "Click me: " + count;
localStorage.setItem("count", count);
};
This is not a server side solution. It's also less reliable as it can be cleared by the user anytime.
javascript runs on the browser and store all the variable in the browser so the scope of a variable is in the browser. you can use local storage but if all user uses the same browser which is not your need so only way to persist data is to save count (data) into the server and fetch count (data) on a load of the page.
you can use firebase real-time database if you don't have any server.
Getting started with Firebase real-time database for the web
As I have understant form your question you want to retain the user click count, there is 3 scenerio
User visits form Single machine Single browser (rare situation)
in this you can use local storage
User visits form Single machine multiple browser
In this case you have to save it in server side
User visits form multiple machine multiple browser
In this case you have to save it in server side
Both case 2,3 are same , you need to save it in server.
A common way to do this , put you counter in db and an REST end point and call that endpoint on page each page load to take the counter form the server and also after clicking update on the server by similar end point
Suggesting learning: Client side : AJAX (Jquery) , Server side : REST API , DB (MySql,ets)

Elegant way of harnessing facebook ads data without api

I was helping one of my relatives with a Facebook campaign for their store.The campaign was a success as we gathered about more than 1000 new likes and a lot of queries.They were happy but I really wanted to do some more with that data like tag those people who liked if their setting allowed or send a message on messenger for arrival of new items.In short keep a track of the all that was happening.The idea is to harness the data so that maximum can be achieved next time on similar campaigns.
I wanted a something simple so that the guys at the store can do it themselves without any fiddling with api.After some trial and error i came up with this js code which can be pasted into console after opening the window which appears when you click link just on the side of like button.
/*a script to get all the people who liked the page
after a facebook campaign. A successful capmpaign will get 1000's of
likes so it will be impossible to load all the names in one go.Also the
list loads progressively with each scroll. So
the code introduces a last element in the json which you have to put in
place of "i" in the given code when you press see more button in
subsequent runs.On my fairly powerful laptop and decent internet I was
not able to get more than 350 persons without a good lag.
The value of i is calculated by trial and error as the data attributes `
before that holds something else(not required) and not the names.I hope
it will be more or less similar in all of them.
This code is to be pasted in the console once the window with all the
likes is opened.*/
var arrayName = document.querySelectorAll('[data-gt]');
var PersonObject={};
try {
for(var i = 55;i<=arrayName.length;i++ ){
var element=arrayName[i];
console.log(element);
var name=element.innerHTML;
// console.log(i)
PersonObject[("name"+i)]=name;
// console.log(PersonObject)
}
}
catch(error){
console.log("error occured at"+i)
}
finally{
PersonObject["lastElement"]=i;
var NamesJson = JSON.stringify(PersonObject)
console.log(NamesJson)
}
I tried to write the gist of code in comments.
Now my real question,this all seems so hacky and patched stuff but not elegant. Isn't there a way for business owners to actually harness this data in more systematic way without the need for any api's or any programming knowledge?

Java script, PHP

I have a scenario where I need to execute a logout function in php, this function deletes the user from DB and informs another application through sockets. This function should be called when the user closes the browser or tab. I have tried various scenarios posted by others and nothing seems to work in chrome(Version 57.0.2987.110) and firefox.
Following is the examples I tried along with links,
My sample Code
<script type="text/javascript">
var str = 'delete';// this will be set to 'Apply' if the form is submitted.
function logout(){
location.href = 'Logout.php';
}
function pageHidden(evt){
if (str==='delete')
logout();
}
window.addEventListener("pagehide", pageHidden, false);
</script >
Examples I tried....
// 1st approach
//window.addEventListener("beforeunload", function (e) {
/// var confirmationMessage = "Do you want to leave?";
// (e || window.event).returnValue = confirmationMessage;
// return confirmationMessage;
// });
// 2nd approach
// window.onbeforeunload = myUnloadEvent;
// function myUnloadEvent() {
// console.log("Do your actions in here")
// }
// 3rd approach
$(window).on('beforeunload', function() {
return 'Your own message goes here...';
});
checked the following urls
1. window.onunload is not working properly in Chrome browser. Can any one help me?
2. https://webkit.org/blog/516/webkit-page-cache-ii-the-unload-event/ - I followed this approach. Tried some other approaches as well.
3. I can't trigger the unload event in Chrome etc....
Any help is much appreciated, because if the user closes the browser an entry remains in the DB and this is not allowing any new user to login.
You shouldn't rely on JavaScript for sever-side code. It's actually entirely possible to achieve what you're looking for, purely with PHP. Just make sure to 'kill' the session before starting it:
session_set_cookie_params(0);
session_start();
session_set_cookie_params(0) will tell the browser that any exisiting session should only exist for another 0 seconds. Essentially, this means that a user will automatically 'log out' immediately. This way, you don't have to rely on client-side code, which is susceptible to all measure of interrupts such as power outages.
Hope this helps! :)
The correct way to logout is related to how they are logged in.
In PHP, the login state is typically managed by sessions. By default the timeout is 24 minutes of inactivity, but you can easily reduce it.
When a user logs out, you typically reset one or more session variables, and, while you’re at it, kill off the current session, and delete the session cookie.
However, you cannot rely on a user to log out, and many typically just wander off. This is why there is always a relatively short timeout on sessions.
If you want to automatically logout when the tab is closed, you will need JavaScript to intercept the process with window.onbeforeunload and then use Ajax to send the logout to the server.
As regards the database, you normally do not record the login state in the database. You may record the login time, and if you like, the logout time, but remember that may be never.

Restrict number of users in a session in vline

Can I restrict the number of users in a session? Is there any option in vline.session? Please guide if this can be done by writing custom javascript.
EDIT:
Referring to https://vline.com/developer/docs/vline.js/vline.MediaSession#examples, a two party call controller is explained. I want to ask is there any way to restrict number of users in a session? There is no such option present in session's docs. Is it supported as a part of the API?
If this can be done using custom javascript, how?
As a part of my effort, I have tried to implement vline-django examples, but could not find a section in documentation that addresses this issue.
EDIT 2: The code that is working for me.
var vlineClient = (function(){
var client, session,
authToken = {{ user|vline_auth_token|safe }},
serviceId = {% vline_service_id %},
profile = {{ user|vline_user_profile|safe }};
// Create vLine client
window.vlineClient = client = vline.Client.create({"serviceId": serviceId, "ui": true});
// Add login event handler
client.on('login', onLogin);
// Do login
client.login(serviceId, profile, authToken);
function onLogin(event) {
session = event.target;
// Find and init call buttons
var callButtons = document.getElementsByClassName('callbutton');
for (var i=0; i < callButtons.length; ++i) {
initCallButton(callButtons[i]);
}
}
// add event handlers for call button
function initCallButton(button) {
var userId = button.getAttribute('data-userid');
// fetch person object associated with username
session.getPerson(userId).done(function(person) {
// update button state with presence
function onPresenceChange() {
button.setAttribute('data-presence', person.getPresenceState());
}
// set current presence
onPresenceChange();
// handle presence changes
person.on('change:presenceState', onPresenceChange);
// start a call when button is clicked
button.addEventListener('click', function() {
person.startMedia();
});
});
}
return client;
})();
How do I move ahead?
Reference: https://vline.com/developer/docs/vline.js/
if i understand correctly the OP is trying to make a multi-user chat room - this is also what i wanted to do with vline and because i wanted a/v chat as well the number of participants should obviously be capped - it appears that the term 'session' is causing the confusion here so i will refrain from using it
i worked around this by creating a fixed number of users in a db and handling authentication
myself before actually associating a visitor with one of the prepared users - so some javascript logs in each visitor as one of those existing 'anonymous' users and sets only a logged_in? flag in the db so that the next visitor will log in as the next vacant user slot and when all slots are occupied the visitor gets a "chat room full - try again later" response
probably not the most elegant solution - for example the visitor chosen usernames are stored client-side and must be re-assigned to one of the user-definable vline session vars so it can be passed along with each message and the logged_in? db flag needs to be reset when the user exits
note that this was almost a year ago so im a bit foggy on exactly what i did but my app (rails) in up on github if youre interested to fork it - also i should add that although this sort of thing wasnt strictly supported by the vline API at the time there were at least some hints that some analogous feature was being prepared for so there may be some API support for this now - i did notice since then that they have released a "chat room demo" app on github and i would expect that their implementation is more concise than mine so you may want to look at that first - my app tho does have a mostly complete UI with gravatars and collaboration is welcomed

Counter Box, Visible for all clients

Hello I need a button for my website, that will start a countdown from 60 secounds to 0, then it should display some text (lets drink, cheers) and go back to start button.
All users must be able to see this countdown, so that when a user start the countdown other users can see this.
It should also display a counter, of howmany user have clicked the button, and joining in on the "button"
I have looked into this, but i need to do Ajax / javascript pulling.
Since my programming skill is still on copy/paste/edit level, I do not know howto get started, I can build the timer, but dont know howto do the pulling.
can anyone help me get started.
Regards
René
Well first of all, you need a stateful backend, to store a usercount. So php+any db.
you mentioned socket.io, build on nodejs.
With nodejs this aint this difficult, because its a single threaded runtime, so you can share variable values to different clients.
your nodejs have to listen to 3 urls:
for passing the basing page ( can be done without nodejs, just url to html)
ajax url for passing clicks on a button from client to backend, returns current count
ajax url to pass the current seconds, returns current count and connected users.
everytime the 2. channels gets called, you need to check , if the countdown is alrdy running. if not: start it, else increase clicked counter.
like this:
//nodejs code
var currendSeconds=60;
var connectedClients = 0;
var threadid;
function clientClickedButton(req, res){ // 2. url
if(currendSeconds==60 || ) {
threadid = setInterval(function(){
currendSeconds--;
if(currentSeconds == 0){
clearInterval(threadid);
}
}, 1000); //your counter
}
connectedClients++;
res.send(currendSeconds);
}
your clientside have to listen to click event on the button, send a ajax req to 2.url and display the returned seconds ( from now on our dont need to request the seconds, just set up a count down clientside, without requesting the current seconds. )

Categories