How to create a Facebook style "Like" system? - php

I've been trying to find an example online of a Facebook style "Like" button but have not been able to find anything like this. What I would like to do is, place a button below an image which the user can press. Once pressed it will increment a value in the database for the image's record, and then reflect the addition on the page by adding + 1 to the existing amount. I can guess this will need PHP, SQL and jQuery to pull off. Problem is I have no idea where to begin. I've created already a PHP script to add to my Like's for a particular image by giving the image ID. I created already a jQuery post button which posts to the PHP and likes the image. The thing I'm stuck on is updating the page to reflect the like.
For starters, I think the code I made to do this so far is completely disgusting lol.
Here is all my code so far.
PHP to output the Likes count and Like button, plus code for addition. $info is the array for the result of my whole image files table:
Echo "<b>Likes:</b> ".$info['likes'] . "</span>";
Echo '<script src="http://code.jquery.com/jquery-latest.js"></script><script type="text/javascript">function test() {$.post("http://stormstorm.com/like.php? id='.$info['fileid'].'")</script>';
Echo '<br /><img onClick="test();" src="img/like.jpg"></p>';
The PHP for the like incremented in like.php:
$id = $_GET['id'];
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id) or die(mysql_error());
The PHP for the liking works fine, I'm happy with that. But the thing to show the liking just sucks badly I think. Thing is I have a list.php which will print the contents of the database one after the other to print all the image listed. So it will print the same replica of the script over and over, typically hard coding the current image ID into the posting. I'm pretty new to this but feel this code sucks, plus it doesn't update the images section.
I was thinking to use Javascript to simply get the Likes element and ++ it but, then it hit me. My list will have over 100+ of these same elements. You can probably tell I might be approaching this the wrong way, and I hope someone can help me out with this.

It looks like you have the general idea down, just a crude implementation of it.
You may want to designate the counter element for each image and update the inner content after the button is pressed...
<img src="xxx.jpg">
<p>
Like <span id="{image_id}_count">150</span>
</p>
where the {image_id} is obviously unique to each image. Pass that to test({image_id}) and then update the html of the count total on success...
function test(id)
{
$.ajax({
url: 'http://stormstorm.com/like.php',
method: 'get',
data: {id: id},
dataType: json,
success: function(data)
{
$('#' + id + '_count').html(data.total);
}
});
}
in your php you would do exactly what you did except return a json encoded array back to the js for update...
$id = mysql_real_escape_string($_GET['id']);
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id);
if(mysql_affected_rows() > 0)
{
$sql = mysql_fetch_assoc(mysql_query("SELECT `likes` FROM `files` WHERE `fileid` = ".$id));
echo json_encode(array('total' => $sql[0]['likes']));
}
Keep in mind this is a VERY POOR implementation of this. The real system should definitely be one that does not allow people to just repeatedly click the button over and over again to increment something for the hell of it. According to your needs, of course, you should limit it by login and even record user information relative to the file they're liking and not just increment a number in the database.
So you would have a relational table that stores information for each like. That way you can query the database to make sure a user has not already liked the file before incrementing the number.
Hope that makes sense.

I think you are headed the right direction. You can return the number of likes after the update call in php and let jquery update the like count. I added some code below as an example.
HTML:
<form name="like_form">
<input type="hidden" name="id" value="<?php echo $info['fileid']; ?>" />
Likes: <span class="like_count"><?php echo $info['likes']; ?></span>
<img src="img/like.jpg" class="like_click" />
</form>
Javascript:
$(document).ready(function() {
$('img.like_click').click(function() {
var form = $(this).closest('form[name=like_form]');
var id = $(form).find('input[name=id]').val();
$.post("http://stormstorm.com/like.php?id='" + id + "', function(data) {
$(form).find('span.like_count').html(data);
});
});
PHP: (*Note: I didn't check syntax but hopefully it will be enough code to understand the idea.)
$id = $_GET['id'];
mysql_query("UPDATE files SET likes=likes+1 WHERE fileid=".$id) or die(mysql_error());
$result = mysql_query("SELECT likes from files where fileid=" . $id) or die(mysql_error());
$row = mysql_fetch_assoc($result);
echo $row['likes'];

Related

Dynamic Row Only Added on First Click

I have an application that seems to work pretty well except for one small glitch that I can't seem to figure out. I am hoping for some help here.
I have a table that I can dynamically add rows to. There are two ways to add rows, some with a checkbox that loads pre-determined data, or an image, which adds a blank row to the table.
The checkbox works great, but the image link only works the first time, and not the next.
This is the image line:
<img src="img/plus.png" width="25" height="25" id="btnAddRow" title="Add New Row" class="idfirst alternativeRow" />
alternativeRow is generated from code from here: http://www.examplet.buss.hk/jquery/table.addrow.php (example #10, but much more complex) and that line is this:
$(".alternativeRow").btnAddRow({oddRowCSS:"oddRow",evenRowCSS:"evenRow"});
The "idfirst" block of jquery code is this:
$(document).ready(function(){
$(".idfirst").click(function(){
result = 0;
id = 0;
jQuery.ajax({
url: 'getItemID.php?q=<?php echo $q; ?>',
success: function(result) {
id = result;
if(result.isOk == false)
alert(result.message);
},
async: false
});
window.location.href='page.php?q=<?php echo $q; ?>&id=<?php echo $id; ?>';
});
});
I do the reload because I want the new number created in getItemID.php to dynamically load. This is important because it also is added to a link that is created within the new row. The code in getItemID is as follows:
$q = $_GET['q'];
$description = $_GET['description'];
$rate = $_GET['rate'];
$hours = $_GET['hours'];
$query = "INSERT INTO items (q, description, hours, rate) VALUES ('".$q."','".$description."','".$hours."','".$rate."')";
$results = mysql_query($query) or die(mysql_error());
$nextId = mysql_insert_id();
echo $nextId;
So my problem is that when I click the image link the first time, everything works great, and I get my blank row, the links in the dynamic row work properly, life is good.
But the moment I press it a second time, the page will reload, but I don't get my new row. It will only return the existing rows before the refresh.
I am wondering if anyone can see something I'm doing wrong and offer any advice. (Yes, I understand that some of this is maybe not the ideal way to make it work, but for the most part it is working the way I need it to...and I've spent tons of hours to make all these moving parts get along).
Thank you in advance for any advice.
I did manage to figure it out.
I was testing this out in IE, which the users will all be using. Same issue in Firefox, which I use.
I came across this article http://www.electrictoolbox.com/jquery-json-ajax-caching/ and once I tried it in Chrome, it turned out to be a browser issue. So I implemented the following solutions:
I added
$.ajaxSetup({ cache:false });
to the top of my script, and for good measure, added
cache: false,
to my ajax call.
Now it works great everywhere.

drop down changes from other drop down with calculation. Jscript / Ajax?

I have a Jscript Query.
I have done a bit of reading and found out that AJAX is just a side server for a lfash script that can be used on Linux with php. (please correct me if I have interperated that wrong)
I have no knowledge on how scripts work so this is new, I have tried a couple of different tries but no luck.
I have one drop down box (Box1) (populated from Database)
I have another box (Box2) for a calculation to insert into my database for other uses on ohter parts of hte site.
I need the Box2 to change the figure when someone changes Box1 dropdown before hitting the submit button.
I think because I have the calcualtion this is getting me stuck... Code is as below... Can someone please help me figure out (I think I need some form of Script to do this.) the answer...
Box1
<td><p>selection 1</p>
<select id="t1_type" name="t1_type">
<?php $result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result)){
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>'; } ?>
Box2
<input name="t1_value" id="t1_value" value="
<?php
$var1 = $row_value['t2_value'];
$var2 = $row_dropdown['t1_number'];
$total = round ($var2 * $var1);
echo "" . $total . "";
?>" />
I hope this is all the code you need, (Let me know if more required)
What it needs to do is show new calculation whenever someone changes the box1 option BEFORE the submit button is clicked, so it submits the correct calculation to the database for future use.
I think it would need pretty much "t2_value" from box2 to change when ever "t2_name changed from box1.
And once again the best link to learn about the solution. (Learnt about Joins now from my last question!! Almost a intermediate user. ;-) )
Edit :
I saw that your second box was a textbox I believe, if thats the problem then you should do something like this
<select id="t1_type" name="t1_type" onchange="change(this);">
<?php
$result = mysql_query("SELECT * FROM `t2` ORDER BY t2_value");
while($valuerow = mysql_fetch_array($result))
{
echo '<option value="'.$valuerow['t2_name'].'">'.$valuerow['t2_name'].'</option>';
}
?>
</select>
This defines your <select> box like you did in your question.
Add an onChange event into your first <select> and then create a function to handle to onChange event. An onChange event fires whenever the user changes the item in the <select> element.
Javascript :
( put this part of the code above the </head> )
<script language="javascript" type="text/javascript">
function change(element)
{
// do here whatever you want
// you can change the value of the <input> box with :
// document.getElementById(element.id).value = your_value
// If you want to see if this part works, then try adding this :
// alert("It works!");
// If you want to get the text of the item which has been selected in Box1 use :
// $("#t1_type option:selected").text();
}
</script>
Note: because PHP is server side, you can't update your Box2 dynamically without a page refresh, Javascript however is Client Side and CAN do this.
Note : the $("#t1_type option:selected").text(); code requires you to include the jQuery library into your script. Be sure to convert this variable to a float, int or double if you want to calculate with it, else the outcome will give NaN (Not a Number)
Tutorial on including jQuery Libary :
http://docs.jquery.com/Tutorials:Getting_Started_with_jQuery
If you're new to JavaScript, you should try some tutorials. The ones at w3Schools.com helpt me alot, but some people say they're not always correct, but anyhow, read some stuff about Javascript to actually know what you are doing, instead of copypasting code :)

Swap images from PHP array with Ajax and also get ID

On my website an user is able to fill in an url. When he fills in the url, he gets all the images src's from that url. I push these src's to an array in php:
array_push($goodfiles,$pic);
Now the user will be able to choose on of the pictures (with a next or prev button) and then save it to the database. The picture that's saved is based on the id of the image in the array. So $goodfiles['0'] means id = "0" and so on.
I want the swapping of the images to work with ajax, so that the pages doesn't have to refresh all the time when clicking the next or previous button. And then when I save the form, I want to know the id of the current image, so that I can save it to the database.
How do I realize this with Ajax (jquery)?
Edit:
This is how I do it right now:
$current_id = $_GET['id'];
if(empty($_GET['id']) || !empty($empty)) { $current_id = 0; }
$prev_id = $_GET['id'] - 1;
if($prev_id < 0){ $prev_id = 0;}
$next_id = $_GET['id'] + 1;
if($next_id > $_SESSION['count']-1 && $_SESSION['count'] != 'empty') { $next_id = $_SESSION['count']-1;}
This is the code for the pagination
And this is the pagination:
<div id="url_pic">
<img src="<?=$_SESSION['pictures'][$current_id]?>" class="img_load"><br>
<? if($_SESSION['count'] > 1) { ?><center><img src="img/add/left.png"> <img src="img/add/right.png"></center> <? } ?>
</div>
So right now my solution doesn't contain any javascript, but it's all php coded. And the page refreshes everytime you want to see the next picture. I want to solve this in ajax, so that you can paginate through the images without a refresh. The way I want it is like this link:
http://d-scribe.de/webtools/jquery-pagination/demo/demo_options.htm
But except for the text, I want to paginate through images.
You probably don't need to use AJAX for this. Simply return a html file containing a JavaScript array, which contains all those image URLs and do the other stuff using JavaScript.
Get back to StackOverflow in case you've a more precise question and hopefully some code, which we can help on ;)
Load a script at the bottom of your php page the user side of the PHP where all your HTML is, above the closing body tag thats something loosely similar to this
<script type="text/javascript">
var myArray = <?php echo json_encode($myPHParray); ?>
</script>
this way when your page loads out it renders with a dynamic javascript json object as a variable that you can work with client side, this removes the need for an AJAX request all together unless your doing stuff with the data your playing with. From first glance Im guessing not really per say. But yea, at the very least its one less transaction to be made when the page is loading.
edit just noticed someone said similar while I was typing out.. Lars.. so I guess this is a follow up to his answer :-D

Php inside a javascript function?

I have a feature on my users inbox that allows users to check/uncheck messages in their inbox that they want to make favourite.
I'm currently testing what happens when a user checks the box (clicks on the image and causes it to go from greyed out to colour meaning the box is checked).
Anyway as you can see from the code below when the box ischecked this url is suppose to be loaded: http://mysite.com/messages/favourite_checked
The message_id of the row the user has checked the box on is suppose to be added onto the end of the url this then loads my controller "messages" and method "favourite_checked" which then passes a variable that grabs the message_id from the url, stores it in a variable then sends it the my model and it is used in a mysql query.
Basically I update the favourites column of my messages table and set it to = 1 where the message_id from url matches the one in the messages table in my database. So yea, where the match is found the "favourite" column in that row is updated to 1. 1 = favourite 0 = not favourite.
Any I just thought I would make it clear what was happening..
My problem is nothing happens when I check the box, nothing is updated so I feel I must be doing something wrong where I try to add the id to the url in the javascript function.
I've tried $(post) also.. nothing happens then also.
Maybe someone can spot it because I really don't know what the problem is.
<script type="text/javascript">
// favourite check box
$('input.favourite:checkbox').simpleImageCheck({
image: '<?php echo base_url()?>images/messages/check.png',
imageChecked: '<?php echo base_url()?>images/messages/unchecked.png',
afterCheck: function(isChecked) {
if (isChecked) {
//query to db from php to update favourite number to 1
$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row): ?><?php $row['id']; ?><?php endforeach; ?>');
}
// else (!isChecked)
// {
// //query to db from php to update favourite number to 0
// $.get('http://mysite.com/messages/favourite_unchecked');
// }
}
});
</script>
I think your basic problem is some confusion about when the PHP is running vs the javascript.
The PHP you put on the page is server side, it will load first, then the javascript will run client-side.
This part here:
$.get('http://mysite.com/messages/favourite_checked'+'<?php foreach ($query as $row): ?><?php $row['id']; ?><?php endforeach; ?>');
Seems like you are wanting this to be dynamic based on what you checked, but I don't see how that url is going to show specifically what you are looking for.
About the PHP:
I think you want to replace this:
<?php $row['id']; ?> // does nothing
with this:
<?php echo $row['id']; ?> // echo's the id
Although I´m not sure that that will work as the loop you have there will generate a strange url, just adding all id's...
About the javascript:
I´m not familiar with the simpleImageCheck() function you are calling, but does it have an onClick or onChange event handler? Otherwise I don´t see your code being run at all.

Best way to delete mysql rows from html page - delete link and php

I'm returning all rows in a table with a while statement and PHP. the rows indicate a list of items. I'd like to include delete links next to each item so users can delete the entries. I'm trying to figure how to go about it in PHP. Can anyone help me write the script.. I'm using procedural.. not OOP.
I'm thinking the link takes users to a process page and back, but I'm not gonna be aware of the entries beforehand, it's all dynamic and the list is always changing.
thanks in advance
Best and save practice is using checkboxes. Google doesn't spider them, users can't put in malicious code easily and it doesn't refresh the page for every delete:
HTML sample:
while ($row = mysql_fetch_assoc($items))
{
echo '<input name="delete['.$row['id'].']" type="checkbox">';
}
PHP processing sample:
$delete = $_POST['delete'];
foreach($delete as $id = $value)
{
$id = mysql_real_escape_string($id);
mysql_query("DELETE FROM table_name WHERE id = $id");
}
Something like this should do the job nicely
Definitely take a look at Ignacio's comment. Since webspiders are able to follow links...naturally they will hit your delete link and destroy any data you have in there.
I'd recommend making it a tiny form with a submit button instead of a link.
Something along the lines of
echo "<form id='form_$id' method='post'>" ..
<input type='hidden' name='id' value='$id' /> ..
<input type='submit' name='submit_$id' value='delete' /> ..
</form>";
Wouldn't using Javascript to delete the record be a possible way to prevent web spiders from following the link?
For example, doing something like:
Delete
<script>
$('#delete_link').click(function() {
document.location.href = "delete.php?id=" + $(this).attr('rel');
});
</script>
This should be fine if web spiders do not follow Javascript links...

Categories