Solved

Php Ajax simple Counter

Posted on 2011-09-30
8
1,835 Views
Last Modified: 2012-05-12
Hi,
I am implimenting a like and dislike Ajax php counter on my website.
There are 2 buttons on my page "Like" "Dislike"

When i click "Like" the database must update itself by incrimenting the value by "1" and must display the new value besides it.

This needs to work with Ajax... Should not refresh the page.
I am wondering what wrong in my code.

have copy pasted the code that i have for the pages...
Also i am writing the columns of my database table.

---index.php begins----

<html>
<head>
<script type="text/javascript">
function ajx(str)
{
if (str=="")
  {
  document.getElementById("txtHint").innerHTML="";
  return;
  }
if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
  xmlhttp=new XMLHttpRequest();
  }
else
  {// code for IE6, IE5
  xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
xmlhttp.onreadystatechange=function()
  {
  if (xmlhttp.readyState==4 && xmlhttp.status==200)
    {
    document.getElementById("txtHint").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","getuser.php?q="+str,true);
xmlhttp.send();
}
</script>
</head>
<body>

<form>
<input type="button" name="buttn" id="buttn" value="submit" onClick="ajx(1)">
</form>

<br />
<div id="txtHint"><b>votes will be displayed here.</b></div>

</body>
</html>
---index.php ends-----

----getuser.php begins-----

<?php
$q=$_GET["q"];

$con = mysql_connect("localhost","user","pass");


if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("mydb",$con);

$sql="SELECT * FROM ajaxtest WHERE id = '1'";

$result = mysql_query($sql);

while($row = mysql_fetch_array($result))
  {
      $oldlike = $row['likes'];
  }
         $newlike =  1 + $oldlike ;
        
         $idf = 1;

$sqlupd = "UPDATE ajaxtext set likes='$newlike' where id='$idf'";
$result1 = mysql_query($sqlupd,$con);

echo $newlike ;

mysql_close($con);
?>
----getuser.php ends-----


ajaxtest is the table name with columns "id", "likes", "dislike" all the colms are itegers.

Thank you,

kansun
0
Comment
Question by:kansun
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 5
  • 3
8 Comments
 

Author Comment

by:kansun
ID: 36891782
I will appreciate if you can provide me a working tested solution.
I have been breaking my head over this simple thing 2 days.

Thank you
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 36892005
Have you got this on a server somewhere so that we can see it in action and suggest some ways to visualize what might be going wrong?
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 36892052
Also, please post the CREATE TABLE statement for the ajaxtest table, thanks.
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:kansun
ID: 36892449
Hi,

this worked for me. I just misspelled the table name while updating.
The problem is that this code now works in firefox but not in ie8.

My god !!!!
any suggestions and solutions..

kansun
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 36892809
http://www.laprbass.com/RAY_temp_kansun.html
<html>
<head>
<title>kansun</title>

<script type="text/javascript">
function getVotes()
{
    var xmlhttp;

    if (window.XMLHttpRequest)
    {
        xmlhttp = new XMLHttpRequest();
    }
    else
    {
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }

    xmlhttp.onreadystatechange = function()
    {
        if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
        {
            document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
        }
    }

    xmlhttp.open("GET","RAY_temp_kansun.php?q=1",true);
    xmlhttp.send();
}
</script>

</head>
<body>

<h2>Vote to see the count <div id="myDiv" style="display:inline;">here</div></h2>
<button type="button" onclick="getVotes()">Vote Now</button>

</body>
</html>

Open in new window

0
 
LVL 110

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 36892819
The backend script.
http://www.laprbass.com/RAY_temp_kansun.php?q=1

You might want to add some sanity checks, but the essential structure seems OK.  Works in FF and IE8.

HTH, ~Ray
<?php // RAY_temp_kansun.php
error_reporting(E_ALL);


// CONNECTION AND SELECTION VARIABLES FOR THE DATABASE
$db_host = "localhost"; // PROBABLY THIS IS OK
$db_name = "??";        // GET THESE FROM YOUR HOSTING COMPANY
$db_user = "??";
$db_word = "??";

// LIVE DATABASE CREDENTIALS
require_once('RAY_live_data.php');


// OPEN A CONNECTION TO THE DATA BASE SERVER
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-connect.php
if (!$db_connection = mysql_connect("$db_host", "$db_user", "$db_word"))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB CONNECTION: ";
    echo "<br/> $errmsg <br/>";
}

// SELECT THE MYSQL DATA BASE
// MAN PAGE: http://us2.php.net/manual/en/function.mysql-select-db.php
if (!$db_sel = mysql_select_db($db_name, $db_connection))
{
    $errmsg = mysql_errno() . ' ' . mysql_error();
    echo "<br/>NO DB SELECTION: ";
    echo "<br/> $errmsg <br/>";
    die('NO DATA BASE');
}
// IF WE GOT THIS FAR WE CAN DO QUERIES

// MANDATORY FOR SAFE QUERIES
$q = mysql_real_escape_string($_GET["q"]);

$sql = "SELECT id, likes FROM temp_kansun WHERE id = $q LIMIT 1";
$res = mysql_query($sql) or die(mysql_error());
$row = mysql_fetch_assoc($res);
if ($row)
{
    $likes = $row['likes'] + 1;
    $upd = "UPDATE temp_kansun SET likes = $likes WHERE id = $q LIMIT 1";
    $upr = mysql_query($upd) or die(mysql_error());
    die("$likes");
}
else
{
    $likes = 1;
    $upd = "INSERT INTO temp_kansun (id, likes) VALUES ($q, 1)";
    $upr = mysql_query($upd) or die(mysql_error());
    die("$likes");
}

Open in new window

0
 

Author Closing Comment

by:kansun
ID: 36893683
thanks for the solution..

that was quick
0
 
LVL 110

Expert Comment

by:Ray Paseur
ID: 36893703
Thanks for the points - it's a great question.  If you want to do some reading you might find this article interesting:
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/PHP_Databases/A_5256-Simple-Vote-Counting-in-PHP-and-MySQL.html
0

Featured Post

Containers & Docker to Create a Powerful Team

Containers are an incredibly powerful technology that can provide you and/or your engineering team with huge productivity gains. Using containers, you can deploy, back up, replicate, and move apps and their dependencies quickly and easily.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
In threads here at EE, each comment has a unique Identifier (ID). It is easy to get the full path for an ID via the right-click context menu. However, we often want to post a short link within a thread rather than the full link. This article shows a…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

696 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question