I'm looking for the easiest way to add a simple like button to my site. Basically, a button that, when clicked - changes to a new graphic (letting you know you clicked it), can't be clicked again, and sends to a php script so the server knows what you liked.
I thought a good technique might be putting a like button inside an iframe so you can click it and the php page could just echo 'thanks for liking this' - but the problem is the iframe has to have a source. I don't want a ton of external files loading into each page. Is there any way I could just have an iframe tag and put HTML inside it without it being external?
Hopefully this makes sense. I do not know your server structure, so its hard for me to build a complete example but this should get you off your feet!
File: Index.php
// query the database and check to see if there is a record for this content piece and ip address
// select count() from statistics where contentId='1' and ip='0.0.0.0' limit 1;
$contentLiked = false;
?>
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" ></script>
<script src="site.js"></script>
</head>
<body>
<? if(!$contentLiked): ?>
like
<? else: ?>
unlike
<? endif ?>
</body>
</html>
File: site.js
$(document).ready(function() {
$('.likeButton').click(function() {
var contentId = $(this).attr('rel');
var link = this;
if(!$(link).hasClass('liked')) {
$.post("like.php", { Id: contentId }).done(function(data) {
if(data) {
$(link).addClass('liked');
$(link).html('liked');
}
});
}
});
});
File: like.php
<?
$contentId = $_POST['Id'];
$timestamp = time();
$usersIP = $_SERVER['REMOTE_ADDR'];
// php code to update the database
// insert: contentId, timestamp, ip address
// if injected then echo / print true;
echo 'true';
?>
You should use jquery animate. It allows you to create an animation on a HTML element that you choose with jquery.
With Jquery, using the 'click' event, you can use the animate effect, and have something like this:
$("#my-button").click(function(){
$(this).animate({
height: 'toggle'
}, 500, function(){
$(this).animate({
height: 'toggle'
}, 500);
});
});
Please see the following example of doing that
Related
i was looking to use a counter on my site so when anyone clicks certain buttons it adds +1 to the counter. I want it so that when you refresh the page the number stays the same, and when a different user clicks the button then it just adds +1 to the counter.
Is this possible? I'm fairly new to Javascript & Jquery so if you could explain it all out it would be great.
Thanks in advance.
Using AJAX and PHP to communicate with a file on the server:
(save this code in a file as index.php and you're good to go!)
There might be an easier way to do it, but I'll show you how to do it using AJAX (n*o page refresh*) and PHP that will allow you to do whatever you want with that counter value in JS.
The provided PHP is not the most secure in the world, but might be secure enough for your needs.
It will create automatically a file called counter.txt if there's none on your server folder (same path as index.php file).
By clicking any of the button elements (it's up tu you to change the jQuery selector) the AJAX get will read from the file the current value stored in your file and will than send an incremented counter value.
<?php
$file = 'counter.txt';
// CREATE FILE
if(!file_exists($file)){
$create = fopen($file, 'w') or die("Could not create the counter database.");
file_put_contents( $file , '0' );
fclose($create);
}
// WRITE FILE
if( isset($_POST['count']) ){
$msg = htmlentities(strip_tags($_POST['count']), ENT_QUOTES);
file_put_contents($file, $msg);
}
?>
<!DOCTYPE html>
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js"></script>
<meta charset=utf-8 />
<title>Flat-File db counter with PHP and AJAX by roXon</title>
</head>
<body>
<button>click me</button>
<button>click me too!</button>
refresh the page , the counter should be memorized from our auto-generated database file! ;)
<br><b></b>
<script>
function addCount( newCounterValue ){
$.ajax( {
type: "POST",
data: {count : newCounterValue},
cache: false,
async: false,
success: function() {
$('b').append('<br>Succesfully sent: '+ newCounterValue);
}
});
}
$(function(){
$('button').click(function(){
$.get('counter.txt', function(data) {
// READ
var counter = parseInt(data, 10) || 0;
$('b').html('Retrieved counter from database = '+ data);
// SEND
addCount( ++counter ); // send preIncremented COUNTER
});
});
});
</script>
</body>
</html>
A client-side solution (will not be available to other users!) would be using HTML5 localStorage
LIVE DEMO
var counter = localStorage.getItem('counter') || 0;
$('button').click(function(){
localStorage.setItem('counter', ++counter);
alert(counter);
});
NOTE this is client side only. You can take a look at PHP how to create a file on the fly and send that value into that file.
On click I'd suggest you to use AJAX to contact that file and read the current value before updating it with PHP.
Click Me
<script src="https://raw.github.com/cowboy/jquery-hashchange/v1.3/jquery.ba- hashchange.js"></script>
<script type="text/javascript">
$(window).hashchange(function () {
//
});
</script>
When Click Me is clicked the URL looks like this "www.mydomain.com/#create=1".
What I am trying to do is us the $_GET in PHP to bring down the parameter. Ex:
<?php echo $_GET['create'];?>
Using the
Click Me
works, but it reloads the page and that is what I am trying to avoid. Any help would be greatly appreciated.
PHP runs on the server. A request has to be sent to the server for PHP to know what is in the query string. You don't need to reload the whole page but you will need to send something to the server, e.g. in an AJAX request and do something with the result.
//java script code
$("#clickme").click(function(event) {
var arr = $(this).attr('href').split('#');
var arr=(arr[1]);
event.preventDefault();
$("#content").load("data.php?"+ arr);
});
//html code
<a id="clickme" href="#create=1">Click Me</a>
<div id="content"></div>
// php code
data.php
There is a new future for that:
window.history.pushState("Remember me!", "Changing the get Parameter...", "?create=1");
You can apply this to all links by using this:
$("a").click(function() {
if ($(this).attr("href").substr(0, 1) != "#") {
$("body").load($(this).attr("href"));
window.history.pushState("Remember me!", "Nothing special", $(this).attr("href"));
return false;
}
});
I need to know how to link (via a regular href anchor on a different page) to content that is inside a tab that is not the default tab. Can this be done? My code will explain hopefully what I require:
My Code:
The following is my profile_edit.php page:
The javascript:
<script src="Javascript/jquery-1.4.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8">
$(function () {
var tabContainers = $('div.tabs > div');
tabContainers.hide().filter(':first').show();
$('div.tabs ul.tabNavigation a').click(function () {
tabContainers.hide();
tabContainers.filter(this.hash).show();
$('div.tabs ul.tabNavigation a').removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(':first').click();
});
$(function () {
var tabs = [];
var tabContainers = [];
$('ul.tabs a').each(function () {
// note that this only compares the pathname, not the entire url
// which actually may be required for a more terse solution.
if (this.pathname == window.location.pathname) {
tabs.push(this);
tabContainers.push($(this.hash).get(0));
}
});
// sniff for hash in url, and create filter search
var selected = window.location.hash ? '[hash=' + window.location.hash + ']' : ':first';
$(tabs).click(function () {
// hide all tabs
$(tabContainers).hide().filter(this.hash).show();
// set up the selected class
$(tabs).removeClass('selected');
$(this).addClass('selected');
return false;
}).filter(selected).click();
});
</script>
The html and PHP (a portion):
<div class="tabs">
<ul class="tabNavigation">
<li>Account</li>
<li>Password</li>
<li>Favorites</li>
<li>Avatar</li>
</ul>
<div id="account_div">
<?php include("personal_info_edit.php"); ?>
</div>
<div id="change_password_div">
<?php include("change_password.php"); ?>
</div>
<div id="favorites_div">
<?php include("favorites.php"); ?>
</div>
<div id="avatar_div">
<?php include("avatar.php"); ?>
</div>
</div>
The following is contained in my change_password_submit.php page:
$update_pass= ("Password changed successfully.");
header("location:profile_edit.php?update_pass=$update_pass#change_password_div");
exit();
By default, whenever profile_edit.php is loaded, the personal_info_edit div is shown and the others are hidden. What do I need to change in the code so that I can reference the 2nd div (ie. change_password div and hide the rest after someone changes their password?
Any help will be greatly appreciated.
This is perhaps not the most elegant solution, but it should work.
You can have PHP sniff your url variables for the existence of a particular variable. I'd probably call this something like 'selectedTabId' or something like that. Then, if that variable exists, you can have jQuery invoke the click action on that tab. You'll want to use switch/case for this rather than just sending through whatever happens to be in the URL, as people can put nasty things there that you don't want your jQuery to run. I won't do that in my example below, for expediency's sake.
This is a notional example...
<?php
if( array_key_exists('selectedTabId',$_GET) ){
$selectedTabId = $_GET['selectedTabId'];
echo "<script type=\"text/javascript\">";
echo "jQuery(document).ready(function(){'#$selectedTabId').click()});";
echo "</script>";
}
?>
Give that a shot and see if it works for you.
I use this thinger: http://flowplayer.org/tools/tabs/index.html
It does that for you. It also does a whole lot on top. It maybe worth implementing instead of your custom solution?
Here's an example of it in action: http://www.estanciaboerne.com/amenities#TAB2entertainment
(This doesn't actually teach you anything, but it is a solution to your problem, so I'm sorry and you're welcome all in one.)
Why am I getting an error in Firebug "u is undefined"?
My page consists of a display of photos and photo gallery as a special separate section in the PHP code divided using the "break".
Photos and photo galleries are displayed using the "Fancybox.js".
The first time when I try to open a photo, everything works fine but when I do it again after I refresh the page the Firebug display error "u is undefined".
The Jquery for the menu that I'm using for display these separate part of the page:
$(document).ready(function(){
$(".menu_rfr").bind('click', function() {
$("#main").html('<img src="img/spin.gif" class="spin">');
location.replace($(this).attr('rel'));
});
$(".menu_clickable").bind('click', function() {
$("#main").html('<img src="img/spin.gif" class="spin">');
$("#main").load($(this).attr('rel'), function(event) {
});
$(".menu_clickable").unbind("click");
});
});
The simplified PHP code looks like:
<?
if (!isset($a)) $a = '';
switch($a)
{
case 1:
default:
?>
<div class="menu_clickable prof_link" id="prof_info" rel="?a=2">Photos</div>
<div class="menu_clickable prof_link" id="prof_info" rel="?a=3">Gallery</div>
<div id="main"></div>
<?
break;//photos
case 2:
?>
<script type="text/javascript">
$("a.group").fancybox({
'titlePosition' : 'over',
'overlayShow':false
});
</script>
<?
<img src="tmb/1.jpg" border="0">
<?
break;
case 3: // photo gallery
?>
<script type="text/javascript">
$("a.groupg").fancybox({
'titlePosition' : 'over',
'overlayShow':false
});
</script>
<?
<img src="tmb/2.jpg" border="0">
<?
break;
}
?>
As I said this is a simplified code, and probably there are some errors in it. I just wanted to show where and how I'm using Fancybox.
Is there a conflict between the jquery code for the menu at the top of the page and this for fancybox or there is some other reason why I keep getting an error in Firebug "u is undefined" after opening the other part of the PHP page and attempts to re-opening photos?
View your HTML source and make sure you don't have FancyBox declared twice. I just had the exact same error pop up in firebug and this is what I found in my source:
<script language="javascript" type="text/javascript" src="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.pack.js"></script>
<link rel="stylesheet" href="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.css" type="text/css" media="screen" />
<script language="javascript" type="text/javascript" src="./ext_scripts/jquery.fancybox-1.3.1/fancybox/jquery.fancybox-1.3.1.pack.js"></script>
Not sure exactly why it happened, but if you nest your include and require_onces in your PHP like I unfortunately did, you can wind up with some very funky Javascript references.
You probably have the fancybox.js script included twice which is causing the issue. Please check all your files and remove the the ones that are not required.
I have this same bug as well - I think it is due to the the 'loading' divs being reset by the cleanup code. I have a VERY nasty fix:
Change:
if ($("#fancybox-wrap").length) {
return;
To: (To skip the multiple-init check)
if (false && $("#fancybox-wrap").length) {
And add:
$.apzFancyboxInit = fancybox_init;
after 'fancybox_init = function() {'
What this does is allow us to call the initialisation routine multiple times; and saves the function pointer to this routine in a global variable. All we have to do now is make sure we call the $.apzFancyboxInit function every time a fancybox is closed. The best place to do this is in the onClosed function handler; so (in my case), my calls look like this:
$.fancybox(
{
'showCloseButton' : true,
'type' : 'ajax',
'onClosed' : function()
{
$.apzFancyboxInit();
},
If you are using a "ripped" template you may find that there are the fancybox generated div written in tho the html template right above the </body> tag.
check if your html output has a div with the id of fancybox-wrap if you have JavaScript disabled, and remove that.
I want to display the image actual view when the mouse is over the thumb sized image. But when the mouse is placed over the first image it appears and then disappears, not the case with the second and following images.
It works perfectly fine in Internet Explorer, but not in Firefox or Chrome.
$file - runs displays all the files in a directory
$id_v - is a simple count on the number of files
$path1 - is the path
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#view').hide();
$('#ig<? echo $id_v; ?>').bind('mouseover', function(ev) {
$('#view').slideDown();
$("#view1").attr({ src: "<? echo $path1.'/'.$file?>" });
});
$('#ig<? echo $id_v; ?>').bind('mouseout', function(ev){
$('#view').slideUp();
});
});
</script>
Please note, my interpretation of your HTML may be completely wrong. Please post all relevant code with your questions. --help us, help you. :op
Please also note (in case you were unaware) that you can edit your question to update with relevant info.
Can't say for sure without seeing HTML, but consider the following:
$('#view').hide();
Here 'view' is an id. IDs must be unique. You can't have them assigned to more than one element.
I'm assuming each item that you want to animate is getting id='view' in your HTML, when you should be doing class='view' in HTML with the following in your javascript:
$('.view').hide()
etc...
Give that a try.
It's hard to tell (for me) without live example...
Did you try to :
preload you images (with css
technique or with preload jQuery
plugin) ?
change mouseover/mouseout by
mouseenter/mouseleave ?
Just for information, in jQuery 1.4, you could use multiple events.
So your code could be rewritten like this :
$('#ig<? echo $id_v; ?>').bind({
mouseover: function() {
$('#view').slideDown();
$("#view1").attr({ src: "<? echo $path1.'/'.$file?>" });
},
mouseout: function() {
$('#view').slideUp();
}
});
I would suggest using the hover method instead of the mouseover and mouseout:
<script language="javascript" type="text/javascript">
$(function() {
$('#view').hide();
$('#ig<? echo $id_v; ?>').bind('hover',
// over
function() {
$('#view').slideDown();
$("#view1").attr({ src: "<? echo $path1.'/'.$file?>" });
},
// out
function() {
$('#view').slideUp();
}
);
});
</script>
I would also suggest (to make your life a little easier), instead of binding new methods to each new id, just assign a class to each one of them and use
<script language="javascript" type="text/javascript">
$(function() {
$('#view').hide();
$('.some-class').hover(
// over
function() {
$('#view').slideDown();
$("#view1").attr({ src: "<? echo $path1.'/'.$file?>" });
},
// out
function() {
$('#view').slideUp();
}
);
});
</script>
There could be a lot of things.
If the image #view is fixed or is showed over the position of the thumbnail it will fire a mouseout in the thumbnail at the moment you show up.
Another thing that may cause that the #view hide instantaneously is that the element #view modifies the position of the whole document, if it is on the top or something like that.
Try to remove the mouseout bind and load the page with Internet Explorer and look how the document is modified.