4 Replies - 3168 Views - Last Post: 03 May 2011 - 06:32 AM

#1 Slice   User is offline

  • sudo pacman -S moneyz


Reputation: 253
  • View blog
  • Posts: 761
  • Joined: 24-November 08

Reloading a number without refreshing the page

Posted 02 May 2011 - 10:51 PM

I'm completely new to Javascript / AJAX and haven't been using php that long either, so bare with me.

Sorry if this is in the wrong forum, It's a little of a php/javascript problem.

I'm trying to create a feature similar to facebooks "like" system.

I have a page with peoples posts in, and when someone clicks on "like", I want to first run the query to insert a new like into the database, then reload just the number of likes, without refreshing the entire page.

I know this way is harder but I want it to work without reloading everything. Here's what I have so far:

function for like (reverse engineered, might be completely wrong..)
function like(){
  $('#postoptions').load('php_files/likecount.php');
}



postoptions.php
<?php

$username = $session->username;

$ifliked = "SELECT * FROM like WHERE postid = '$postid' AND username = '$username'";
$runqb = mysql_query($ifliked) or die(mysql_error());

if(mysql_fetch_array($runqb) > 0){
	echo "<span class='potv'>like[";
	include("php_files/likecount.php");
	echo "]</span>";
}else{
	echo "<a class='pot' onclick='like()' href='#'>like[";
	include("php_files/likecount.php");
	echo "]</a>";
}

?>



likecount.php
<?php
$countLikes = "SELECT COUNT(*) AMOUNT FROM like WHERE postid = '$postid'";
$runCount = mysql_query($countLikes) or die(mysql_error());
$rCount = mysql_fetch_assoc($runCount);
$amo = $rCount['AMOUNT'];

echo "$amo";

?>



I know that at the moment there is no query to add an entry to the database when clicking on the like link, but I'm not too sure how to put it. I tried putting this:

	$addLike = "INSERT INTO	like (username, postid) VALUES ('$username','$postid')";
	$run = mysql_query($addLike) or die(mysql_error());



but because the posts are loaded with a while loop, clicking like on one made me like all of them on that page.

I'm pretty sure something is totally wrong here, but I have no idea where to go with this now :( I though reloading the "likecount.php" page would reload the count for the page?

Is This A Good Question/Topic? 0
  • +

Replies To: Reloading a number without refreshing the page

#2 Atli   User is offline

  • Enhance Your Calm
  • member icon

Reputation: 4240
  • View blog
  • Posts: 7,216
  • Joined: 08-June 10

Re: Reloading a number without refreshing the page

Posted 03 May 2011 - 01:47 AM

Hey.

Where are the $session and $postid variables in your PHP coming from? I can't see you defining them anywhere.

Also, while this actually works, it's a little odd:
if(mysql_fetch_array($runqb) > 0)

You are fetching an array of data, and comparing it to the number 0. It so happens that the function returns FALSE if there is no data, and PHP casts FALSE to 0 when compared like that, so this doesn't cause problems (yet), but you really should be using mysql_num_rows in that situation.

Or, better yet, do what you do in your likecount.php file. Instead of fetching ALL the data for the rows you are counting, just to count how many rows there are, use the COUNT() function in your SQL query and use that value. Much more efficient.
Was This Post Helpful? 1
  • +
  • -

#3 Slice   User is offline

  • sudo pacman -S moneyz


Reputation: 253
  • View blog
  • Posts: 761
  • Joined: 24-November 08

Re: Reloading a number without refreshing the page

Posted 03 May 2011 - 05:52 AM

View PostAtli, on 03 May 2011 - 02:47 AM, said:

Also, while this actually works, it's a little odd:
if(mysql_fetch_array($runqb) > 0)

You are fetching an array of data, and comparing it to the number 0. It so happens that the function returns FALSE if there is no data, and PHP casts FALSE to 0 when compared like that, so this doesn't cause problems (yet), but you really should be using mysql_num_rows in that situation.


Good catch, I actually did mean to use mysql_num_rows for that :)

View PostAtli, on 03 May 2011 - 02:47 AM, said:

Hey.

Where are the $session and $postid variables in your PHP coming from? I can't see you defining them anywhere.


Sorry I didn't post the main page where the like button will be placed:
home.php
include("include/session.php");
include ("php_files/tsf.php");
$con = mysql_connect("localhost","****","********");
if (!$con)
	{
		die('could not connect: ' . mysql_error() );
	}
mysql_select_db("chronicleme", $con);
$username = $session->username;

if($session->logged_in==false){
	echo "<meta http-equiv='refresh' content='0;URL=index.php'>";
}else{

$querysubs = "SELECT COUNT(*) AMOUNT FROM subs WHERE username='$username'";
$qsreturn = mysql_query($querysubs);
$subcount = mysql_fetch_assoc($qsreturn);
$querycount2 = "SELECT COUNT(*) AMOUNT FROM subs WHERE userrec='$username'";
$qsreturn2 = mysql_query($querycount2);
$scount2 = mysql_fetch_assoc($qsreturn2);

//HOW MANY POSTS PER PAGE
$rowsPerPage = 20;

//SET PAGE TO 1 BY DEFAULT
$pageNum = 1;

// IF ANOTHER PAGE IS SELLECTED ..
if(isset($_GET['page']))
{
    $pageNum = $_GET['page'];
}

// counting the offset
$offset = ($pageNum - 1) * $rowsPerPage;



//GET POSTS FROM USERS THAT THE LOGGED IN USER IS SUBSCRIBED TOO
$getpubs = "SELECT posts.postid, posts.username, posts.posttitle, posts.postcontent, posts.posttime, subs.username, subs.userrec 
			FROM posts, subs 
			WHERE posts.username = subs.userrec 
			AND subs.username = '$username' 
			AND posts.publish = '1' 
			ORDER BY posttime DESC 
			LIMIT $offset, $rowsPerPage";
			
$gpresult = mysql_query($getpubs) or die(mysql_error()); // RUN QUERY



if(mysql_num_rows($gpresult) > 0){	
	while($row = mysql_fetch_array($gpresult)){
		$postid = $row['postid']; //SET POST ID
		//COUNT HOW MANY COMMENTS THE POST HAS
		$querycomments = "SELECT COUNT(*) AMOUNT FROM comments WHERE postid='$postid'"; 
		$return = mysql_query($querycomments);	
		$disp = mysql_fetch_assoc($return);
		$numcomments = $disp['AMOUNT'];
		
		$date = $row['posttime'];//FETCH THE DATE
		$user = $row['userrec'];
		$posttitle = $row['posttitle'];//SET POST TITLE
		$postcontent = $row['postcontent'];	//SET POST CONTENT
		$postuser = $row['username']; 	
		echo "<div class='newsbox'>";
		echo "<a class='ptitle' href='comment.php?postid=$postid&user=$user'>$posttitle</a>";
		echo "<a class='byname' href='userpage.php?user=$user'> by $user</a>";
		echo "<span class='datetime'>";
		echo formatDate($date);
		echo "</span>";
		echo "<p>$postcontent</p>";
		echo "<a href='comment.php?postid=$postid&user=$user' class='pot'>comments[";
		echo $disp['AMOUNT']; //DISPLAY AMOUNT OF COMMENTS
		echo "] </a>";		
		if($user == $session->username){ // CHECK IF POST IS BY LOGGED IN USER TO DISPLAY EXTRA OPTIONS: DELETE AND EDIT
			include("php_files/useroptions.php");
		}else{
			echo "<div class='postoptions'>";
			include("php_files/postoptions.php"); //SHOW JUST THE LIKE OPTION FOR THE POST
			echo "</div>";
		}
		echo "</div>";
	}
}else{
	echo "<p>You currently have no posts to view. Subscribing to users will show their posts here.</p>";
}




And inside session.php is just the php to set and view cookies and manage logged in users.

So I just want the like area to be completely independently refreshing. What's the best way to run a query and +1 like when someone clicks the link?

This post has been edited by Slice: 03 May 2011 - 05:53 AM

Was This Post Helpful? 0
  • +
  • -

#4 Atli   User is offline

  • Enhance Your Calm
  • member icon

Reputation: 4240
  • View blog
  • Posts: 7,216
  • Joined: 08-June 10

Re: Reloading a number without refreshing the page

Posted 03 May 2011 - 06:22 AM

Ok, I see.

The AJAX request is completely independent from the request that created the Javascript. Once your like() function is called on the browser, the $postid from the original call to the home.php file is long gone.

If you need a value from the original PHP script to be available in the PHP script called by AJAX, you need to pass it through the AJAX call itself. (Using a session is also an option, but a poor one in this case.)

For instance, if you were to do this to your like() function:
function like(postid){
  $('#postoptions').load('php_files/postoptions.php', { "postid" : postid } );
}


You could pass the $postID to it from PHP via the onclick handler, like so:
echo "<a class='pot' onclick='like({$postID})' href='#'>like[";



Then all you have to do is fetch the value in your postoptions.php code, where it would be available as $_POST['postid'].
<?php
// Makes it so that if the $postid is already set
// you will not replace it. (So you can include this
// script in your home.php file as well as use it
// for you AJAX request.)
if (!isset($postid) && isset($_POST['postid'])
    $postid = (int) $_POST['postid'];

$username = $session->username;
// etc...



Note that I changed the URL for the AJAX call from "php_files/likecount.php" to "php_files/postoptions.php". I'm assuming you want the whole like[X] thing shown, not just the number you would get from "likecount.php". -- The jQuery load() method replaces the contents of the elements you specify with what the AJAX request returns, so if you only return a number, that is all it will show.

Also, you have this in your home.php code:
echo "<div class='postoptions'>";

Is this the DIV you want the load() call to replace? If so, then you would have to either do $(".postoptions").load(...), or replace the "class" attribute with an "id" attribute. - The # selector in jQuery looks for IDs, where the . selector looks for classes.
Was This Post Helpful? 1
  • +
  • -

#5 Slice   User is offline

  • sudo pacman -S moneyz


Reputation: 253
  • View blog
  • Posts: 761
  • Joined: 24-November 08

Re: Reloading a number without refreshing the page

Posted 03 May 2011 - 06:32 AM

View PostAtli, on 03 May 2011 - 07:22 AM, said:

Also, you have this in your home.php code:
echo "<div class='postoptions'>";

Is this the DIV you want the load() call to replace? If so, then you would have to either do $(".postoptions").load(...), or replace the "class" attribute with an "id" attribute. - The # selector in jQuery looks for IDs, where the . selector looks for classes.


Another great catch :bigsmile:. It was meant to be a class attribute :P

Thanks for the great reply, it's helped me understand a lot more about how AJAX actually works.

I'll post back if I run into any problems implementing your solution :D
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1