Solved

Php Ajax simple Counter

Posted on 2011-09-30
8
1,712 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
  • 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 108

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 108

Expert Comment

by:Ray Paseur
ID: 36892052
Also, please post the CREATE TABLE statement for the ajaxtest table, thanks.
0
 

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
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 108

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 108

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 108

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

Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

Join & Write a Comment

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article is meant to give a basic understanding of how to use R Sweave as a way to merge LaTeX and R code seamlessly into one presentable document.
Learn the basics of modules and packages in Python. Every Python file is a module, ending in the suffix: .py: Modules are a collection of functions and variables.: Packages are a collection of modules.: Module functions and variables are accessed us…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

758 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

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now