Solved

Php Ajax simple Counter

Posted on 2011-09-30
8
1,747 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 109

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 109

Expert Comment

by:Ray Paseur
ID: 36892052
Also, please post the CREATE TABLE statement for the ajaxtest table, thanks.
0
Master Your Team's Linux and Cloud Stack!

The average business loses $13.5M per year to ineffective training (per 1,000 employees). Keep ahead of the competition and combine in-person quality with online cost and flexibility by training with Linux Academy.

 

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 109

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 109

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 109

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

DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

Question has a verified solution.

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

Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Learn the basics of lists in Python. Lists, as their name suggests, are a means for ordering and storing values. : Lists are declared using brackets; for example: t = [1, 2, 3]: Lists may contain a mix of data types; for example: t = ['string', 1, T…
Learn the basics of if, else, and elif statements in Python 2.7. Use "if" statements to test a specified condition.: The structure of an if statement is as follows: (CODE) Use "else" statements to allow the execution of an alternative, if the …

776 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