?
Solved

Php Ajax simple Counter

Posted on 2011-09-30
8
Medium Priority
?
1,878 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 111

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 111

Expert Comment

by:Ray Paseur
ID: 36892052
Also, please post the CREATE TABLE statement for the ajaxtest table, thanks.
0
TCP/IP Network Protocol Cheat Sheet

TCP/IP is a set of network protocols which is best known for connecting the machines that make up the Internet. The truth is that TCP/IP is one of the oldest network protocols and its survival is mainly based on its simplicity and universality.

 

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 111

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 111

Accepted Solution

by:
Ray Paseur earned 2000 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 111

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

Learn by Doing. Anytime. Anywhere.

Do you like to learn by doing?
Our labs and exercises give you the chance to do just that: Learn by performing actions on real environments.

Hands-on, scenario-based labs give you experience on real environments provided by us so you don't have to worry about breaking anything.

Question has a verified solution.

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

Build an array called $myWeek which will hold the array elements Today, Yesterday and then builds up the rest of the week by the name of the day going back 1 week.   (CODE) (CODE) Then you just need to pass your date to the function. If i…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
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.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

762 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