Is it possible to use JQuery & PHP to create a "like" button that a user could click and it would add +1 to a "number of likes" database (or even text file) and disable the "like" button for that user so that the user could only click it once? I was browsing around and found some information about writing cookies with JQuery:
http://jquery-howto.blogspot.com/2010/09/jquery-cookies-getsetdelete-plugin.html
Perhaps, when a like button is clicked, it could write a cookie to the user's computer that would prevent them from future clicks? It just basically needs to be that the user could click the like button, it adds a count to some type of database, and it disables the button for the user. Pretty simple I would imagine - there may already be some type of plugin for this, but I haven't found any. Any ideas?
Thanks!
jquery:
$("button").click(function(){
$(this).remove();
$.post('count.php');
});
though the user can just reload the page, so any real validation needs to happen on the php side.
You may want to look at jQuery's one() function. It allows you to bind an event for only one invocation. Here's an example I'd run on page load.
if (likedBefore) {
$("button").addClass("liked");
}
else {
$("button").one("click", function() {
$(this).addClass("liked");
$.post("count.php");
});
}
Validating server side is a bit more difficult. It really depends on how secure you need this to be.
Related
So the SMEs at my current place of employment want to try and disable the back button for certain pages. We have a page where the user makes some selections and submits them to be processed. In some instances they have to enter a comment on another page.
What the users have figured out is that they don't have to enter a comment if they submit the information and go to the page with the comment and then hit the back button to return to the previous page.
I know there are several different solutions to this (and many of them are far more elegant then disabling the back button), but this is what I'm left with. Is it possible to prevent someone from going back to the previous page through altering the behavior of the back button. (like a submit -> return false sorta thing).
Due to double posting information I can't have it return to the previous page and then move to the current one. I can only have it not direct away from the current page. I Googled it, but I only saw posts saying that it will always return to the previous page. I was hoping that someone has some mad kung foo js skills that can make this possible.
I understand that everyone says this is a bad idea, and I agree, but sometimes you just have to do what you're told.
Don't do this, just don't. It's bad interface design and forces the user's browser to behave in a way that they don't expect.
I would regard any script that successfully stopped my back button from working to be a hack, and I would expect the IE team to release a security-fix for it.
The back button is part of their program interface, not your website.
In your specific case I think the best bet is to add an unload event to the page that warns the user if they haven't completed the form. The back button would be unaffected and the user would be warned of their action.
Nah, you're doomed. Even if you pop the page up in some different browser and hid the back button, there's always the Backspace key.
The problem with marketing guys and analyst types is that some of them do not understand the fundamental concept of the web being stateless. They do not understand that the page is totally, totally unaware of the browser using it and absolute control of the browser is totally outside the capability of web pages.
The best way to discourage your users to hit the back button is to make sure that your page loses all its data when they press back, e.g., the comment page is the only point where the data can be saved, and if they do press the back button they have to do everything all over again (think along the lines of pragma: nocache).
Users will complain, sure, but they are the reason that this godforsaken requirement exists, right?
I've seen this before:
window.onBack = history.forward();
It is most definitely a dirty hack and, if at all possible, I would attempt to not disable the back button. And the user can probably still get around it quite easily. And depending on caching, there is no telling if the server code will be processed or if the cached page with JavaScript will run first.
So, yeah, use at your own risk :)
I came up with a little hack that disables the back button using JavaScript. I checked it on chrome 10, firefox 3.6 and IE9:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<title>Untitled Page</title>
<script type = "text/javascript" >
function changeHashOnLoad() {
window.location.href += "#";
setTimeout("changeHashAgain()", "50");
}
function changeHashAgain() {
window.location.href += "1";
}
// If you want to skip the auto-positioning at the top of browser window,you can add the below code:
window.location.hash=' ';
var storedHash = window.location.hash;
window.setInterval(function () {
if (window.location.hash != storedHash) {
window.location.hash = storedHash;
}
}, 50);
</script>
</head>
<body onload="changeHashOnLoad(); ">
Try to hit the back button!
</body>
</html>
Do you have access to the server-side source code? If so, you can put a check on the first page that redirects to the second page if the information has been submitted already (you'll need to use sessions for this, obviously). At a former job, this is how we handled multi-step applications (application as in application for acceptance).
Could you move the comment to the previous page and make it a required field there?
Disabling the back button will not work.
Because of the security isolation of javascript in the browser, you cannot change what the back button does.
Perhaps you could store something in the user's session that indicates that a comment is needed, and have any page in the app that the user tries to load redirect to the comment page?
What if the user closes their browser when he/she gets tot he comment page?
I know that you have not been given a choice here, but since what they are asking for seems to be impossible...
Perhaps you could just not consider the item as completed until the user enters comments. Thus, you would need to keep track of both in-progress items and completed items, and make that distinction in the UI, but this might be the most robust method.
Or just put the comment field on the form page?
What the users have figured out is
that they don't have to enter a
comment if they submit the information
and go to the page with the comment
and then hit the back button to return
to the previous page.
Then they are probably also smart enough to type 'no comment' into the comments field.
You can try to force people to add comments, but you will probably just end up with bad unusable software, annoyed users, and still not get comments. This is usually a good time to take a step back and reconsider what you are doing from the users' point of view.
Disabling the back button seems kind of a "brute force" approach.
Another option would be that you could jump out to a modal dialog that doesn't have command buttons, walk users through the workflow, and close the dialog when the process is complete.
You should secure your application against double submission instead of breaking user interface to hide the bug.
There simply is no reliable way to do this. You cannot guarantee that 100% of the time you can stop the user from doing this.
With that in mind, is it worth going to extremely exotic solutions to disable "most" of the time? That's for you to decide.
Good luck.
AS a simple solution: try this one. Insert an update panel and a button in there and use javascript to hide it and then press it on page load. Yes I understand that it will cause your page to post back on load and may not work if javascript is disabled but certainly will help you achieve a half decent response to the back button issue. Andy
You can prevent them from going back to the previous page. location.replace() replaces the current page's history entry with a new page, so...
page1.html: user clicks a link that goes to page2.html
page2.html: user clicks a link that calls location.replace('page3.html');
page3.html: user clicks back button and goes to page1.html
This may not fit well with doing a POST, but you could post the data to a web service via AJAX, then call location.replace()
If you are starting a new web app from scratch, or you have enough time to rework your app, you can use JavaScript and AJAX to avoid the browser's history, back, and forward functions.
Open your app in a new window, either before or immediately after login.
If you wish, use window options to hide the nav bar (with the back and forward buttons).
Use AJAX for all server requests, without ever changing the window's location URL.
Use a simple web API to get data and perform actions, and render the app using JavaScript.
There will be only one URL in the window's history.
The back and forward buttons will do nothing.
The window can be closed automatically on logging out.
No information is leaked to the browser history, which can help with security.
This technique answers the question, but it also contradicts best practice in several ways:
The back and forward buttons should behave as expected.
An app should not open new browser windows.
An app should still function without JavaScript.
Please carefully consider your requirements and your users before using this technique.
I don't see this solution :
function removeBack(){
window.location.hash="nbb";
window.location.hash="";
window.onhashchange=function(){window.location.hash="";}
}
Is there any way to catch a page refresh and pause it for a certain time period using javascript, jquery or whatever?
This is necessary to prevent accidentally pressing the refresh key amid an important work which is one-time ,and needs to be processed and saved before the page gets refreshed.
In one of my previous questions posted in this forum, I had to face this issue, which is still unsolved, at a certain point during the discussion of the question. I think posting it as an individual question is quite worth it. The said question is here .Edit part of the question contains the issue.
Scripting language is php. Or should I use any other language to achieve the goal?
It appears this can be accomplished with window.onbeforeunload() like in this example.
<script type="text/javascript">
window.onbeforeunload = function() {
return "You sure you want to leave? You will lose all your work!";
}
</script>
I don't think there is a way to stop or pause the page refresh. Yes, you can give a warning, but to be safe you just fill user's cookie with current state of form's input fields with javascript at every form field change. User pressed radiobutton? Cookies updated. User updated input field? Cookies updated.
Then, on page load, just have php or javascript read cookies and fill the form.
i think you should use:
<body onbeforeunload="return 'are you sure you want to move away from this page?';">
I am new to Jquery. I have a doubt:
For example, in a web page as voting, if you click a button, a counter is incremented by +1. Now, how to draw the url of the button on a website? Therefore, if we provide the url to others, and just click on the URL, the counter should increase by 1 on the website.
Best example of this is FaceBook LIKE.
I prefer to use jQuery, PHP and MySQL
It's a little bit difficult to understand what you're trying to ask but here's my take on it.
Scenario
You have a page at http://mywebsite.com/rating which contains 5 items you can rate on.
Solution
There are two events here that point to the same server side code.
What you need to do is assign an identifier to your button/product/whatever you're trying to rate. So you might have something like this <button ratingname="button1">Rate me!</button>
Now you will have a jQuery function that will use AJAX to communicate with your server and store the increment in the database. This jQuery function will be invoked via an event handler for the button and by going to this url: http://mywebsite.com/rating#button1.
Once your page loads you should check the hash for a value and if one is found then invoke the original jQuery function. You may want to additionally check if the value for the hash is a valid rating button value. (Note you could also use a query string).
I would do it using ajax, and a server side program to record votes.
You could design the page with any look-and-feel. Then add the ajax code to talk to your server-side program and maybe show the user the current votes.
?id=642&point=1
It’s a POST, not a GET, so it could only be done from a form or AJAX, not a simple URL.
//Vote update
$.post(
"http://example.com/folder/vote.php", // url
{ id: 642, point : 1 }, // post-data
function(data){ // response
$("#resultBox").addClass("done"); // show msg
}
);
More reading at http://api.jquery.com/jQuery.ajax/
I have a form with a save button, but i want users to be able to come back to the form at anytime to finish filling it in. I would like to know if its possible to bypass the save button, so the user fills part of the form in, as soon as they navigate away from the page or close their browser it will save the form automatically to resume next time.
What would be the best way to implement this? Thanks in advance for any help, its much appreciated.
I have seen some javascript examples but have seen issues with cross browser support.
You can use an AJAX Call on unload like this:
window.onunload = myfunc();
function myfunc() {
alert("i am closing now");
// Your AJAX Call that saves your data (e.g. all input fields)
}
Jquery plugin, works a treat for autosave function.
http://plugins.jquery.com/project/jquery-autosave
More info here:
http://rikrikrik.com/jquery/autosave/#examples
include plugin:
<script type="text/javascript" src="scripts/jquery.autosave.js"></script>
$('form.formnamehere').autosave({
'interval': 20000
});
Auto submits form without page refresh.
I have set my interval to one second (1000) so the form gets saved every second. Therefor if the user exits the form after editing then it has autosaved.
I need to implement a links-click counter, that will count the number of clicks on the link...
Right now what i am doing is, i am linking the href to redir.php, which will increase the counter in DB and then using header('Location:'); I am redirecting it to the correct URL.
This works but it is certainly not the best approach. In an effort to make my code efficient, how can I make this link counter better? AJAX?
Not much exp with ajax so I wondering how to do in ajax or is there any other better method...
I do not want someone to write a bot script that would make multiple requests to the redir.php and mess up the stats.
You can use
Javascript to make a Ajax call to your "counter.php"
Add a Javascript code (like Google Analytic) on each page to post on the database
Create a "cron job" to analyse the "access_log" (if you count the link in the same domain, server)
Add a PHP code to update the database when each page is generate.
But I think the first javascript method is the best one.
Add a class on the link to spy
Add a "Event handler" to create a AJAX post
Create a simple PHP script to update the database.
Aka
If you links are generated from a source like a CMS instead of by hand, you could pass the link ID to your URL and on the loading of the next page count increment that the link has been clicked. Going this way would require that you reload (without the link ID) the page after that step to make sure that someone copying the link would not make the counter increment needlessly.
This method is bulletproof if your user has javascript enabled, but if your user does have javascript enabled, you could still do the method stated above and through a client side layer, bypass the whole thing and send it through AJAX.
This might seems like redundancy, but this way, you accelerate your process for most of your visitors (without the redirect since you do it through AJAX) and in the case that the javascript doesn't work or is disabled, you have a fail proof system that would avoid missing any click
Building off of #Akarun's answer, here is sample code (in jQuery) for adding a "listener" onto link clicks with "spy" class. Note that I load an image instead of attempting a $.post or other AJAX event -- this is because those won't complete by the time the person navigates away from the page (which clicking on a link is bound to do in most cases), whereas the browser will get off a request for the image in time. It's still a normal PHP script, the browser just thinks it's loading an image.
$(document).ready(function() {
$('a.spy').mousedown(function(event) {
var page_url = "<?=$_SERVER['PHP_SELF']?>";
var target_url = $(this).attr('href');
if(target_url != "#" && target_url != "javascript:void(0);")
new Image().src= "/welcome/track_link/?page_url=" + escape(page_url) + "&target_url=" + escape(target_url);
return true;
});
});
Have you thought of mobile users and other devices?
I believe your first implementation is completely adequate and secure.
You completely control the counting and there is no issue of user manipulation.
It works predictably also.
After all, the ajax will just do the samething in counter.php; Read and update the database. Stay with your present implementation.
Do it the way Google does it:
Waterfront Rentals
A javascript function. The passed code aids security.
Actually looking at the Google source they load an image with the URL as a parameter
window.clk=function(e,b,a,k,i,c,j)
{
if(document.images) {
b=encodeURIComponent||escape;a=new Image;var f=window.google.cri++;window.google.crm[f]=a;a.onerror=a.onload=a.onabort=function() {
delete window.google.crm[f]
};
var d,g,h;if(google.v6) {
d=google.v6.src;g=google.v6.complete||google.v6s?2:1;h=(new Date).getTime()-google.v6t;delete google.v6
}if(c&&c.substring(0,6)!="&sig2=")c="&sig2="+c;a.src=["/url?sa=T&source=",google.sn,"&cd=",b(i),google.j&&google.j.pf?"&sqi=2":"","&ved=",b(j),e?"&url="+b(e.replace(/#.*/,
"")).replace(/\+/g,"%2B"):"","&ei=",google.kEI,d?"&v6u="+b(d)+"&v6s="+g+"&v6t="+h:"",c].join("")
}
return true
};