View Full Version : Making a Favorite's Star/Button

12-27-2011, 07:13 AM
I am implementing a favorite's click-able link similar to what Gmail uses, however, I am having some trouble with the JS functioning. I am currently using a Jquery library.

I have a homepage.php whereby I have list of user posts. All I want to do is add a simple star, whereby if someone clicks on that star it updates a mysql database table (userposts) column (p_fav) to either a '1' for favorite or '0' as not-favorite. The table is already setup, I just need help with the javascript/jquery. I made some implementation by searching through google (see below) but it is not working.

Here is what I have, if someone can offer up something simpler as opposed to trying to modify this, I'd be glad to change in a heartbeat (actually it seems that what I have is such a mess, that I'd prefer a better solution):


//database connect etc...
// query to get user posts from userposts table (code not shown)

//make favorite links
$mark_fav ='
<a href="#article-15" class="favorite">
<img src="images/fav_star_1.png" alt="Make it a favorite!" />
<a href="#image-12" class="favorite">
<img src="images/fav_star_1.png" alt="Make it a favorite!" />

//create a list of posts
$post_list .= '
<li>' . $outputList . ' </li>
<li>' . $mark_fav . '</li>

// make_favorite function
function make_favorite($item_type, $item_id){
$sql = mysql_query("SELECT p_fav FROM userposts WHERE post_id='$post_id'") or die (mysql_error());
while($row = mysql_fetch_array($sql)){
$isitafav = $row["p_fav"];
if ($isitafav != 1) {
$sql1 = mysql_query("UPDATE userposts SET p_fav='1' WHERE post_id='$post_id'");

// set header
header('Content-type: application/json');

// ensure to cleanse these inputs
$item_type = $_POST['item_type'];
$item_id = $_POST['item_id'];

if(make_favorite($item_type, $item_id)){
$response = array('ok' => true, 'message' => 'Huzza!');
else {
$response = array('ok' => false, 'message' => mysql_error());

// the magic?
echo json_encode($response);

<script src="jquery.js" type="text/javascript"></script>
<script src="jquery.make_favorite.js" type="text/javascript"></script>
<script type="text/javascript">
<?php echo "$post_list"; ?>

And here is the js file (jquery.make_favorite.js)

$.fn.make_favorite = function(){

var callback = function(response){

return this.each(function(){

var params = {
item_type: $(this).attr('href').match(/\w+/)[0], // 'article'
item_id: $(this).attr('href').match(/\d+/)[0] // 15

$.post('/favorite.php', params, callback, 'json');

// stop event propagation
return false;

It seems like this should be a lot simpler, and hopefully I can get a solution that would fit in my homepage.php file, instead of having a separate js file.