0

Possible Duplicate:
pass php variable to javascript

I want to compare the click count(s) clicked by the users with the data saved in database. I am not sure how to proceed to pass the value of the HTML "clicks" to compare with "counts" in PHP.

<html>
<script type="text/javascript">

 var count = 0;

 function countClicks() 
 {          
    count = count + 1;
    document.getElementById("clicks").innerHTML = count;
 }  
</script>

<?php
    if(empty($counts)){
?>

<script type="text/javascript">

    alert("Count is empty!!");

</script>   

<?php

} else { 

$data = mysql_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'"); 
$info = mysql_fetch_array($data);
//compare $data with the clicks
echo 'same!';
}
?>

<body>
<a href="javascript:countClicks();">Count Clicks</a>
<input type="button" onclick=countClicks() value="Click"/>
<p id="clicks">0</p>
</body>
</html>
Community
  • 1
  • 1
CK Tan
  • 596
  • 2
  • 10
  • 25
  • Please, don't use `mysql_*` functions to write new code. They are no longer maintained and the community has begun [deprecation process](http://goo.gl/KJveJ). See the *[red box](http://goo.gl/GPmFd)*? Instead you should learn about [prepared statements](http://goo.gl/vn8zQ) and use either [PDO](http://php.net/pdo) or [MySQLi](http://php.net/mysqli). If you can't decide which, [this article](http://goo.gl/3gqF9) will help you. If you pick PDO, [here is good tutorial](http://goo.gl/vFWnC). – Waleed Khan Jan 07 '13 at 15:15

2 Answers2

2

You are using PHP and Javascript in the wrong way. PHP is a serverside language. which means it runs before the page even loaded on the browser.

You will have to create a javascript click counter and put its values into a hidden formfield. Then use a submit button to send the information to the server (PHP). Then let PHP do the checks and selections from the database and return an answer.

Another solution is to use javascript AJAX, but I do recommend first trying the above.

Chris Visser
  • 1,607
  • 12
  • 24
0

The best way to proceed would be to make an Asynchronous JavaScript and XML call (AJAX). PHP is a server-side language, which is executed before the HTML (thus, before Javascript) is built and shown to the browser.

Therefor, the only way for Javascript to exchange variables and data with PHP is to make an AJAX call (you could always reload the page with a form submit or with session variables and cookies, but this isn't the best way to go if action is repeated too often.

IN AJAX, you can make another PHP page that will check both values and return whatever you want. The response can be stored in a Javascript variable, or even in JSON.

I suggest you to read more about AJAX and also get to know what is PHP how to use it.


Edit: After reading your comment, I decided to put a simple example down here.

Javascript (in your HTML page)

var xmlhttp;

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)
  {
     /*Here you should do what you want. 
      xmlhttp.responseText is the content of your PHP answer! */ 

     var result = xmlhttp.responseText;
     //I am parsing a JSON response, which is a specific, universal language
     //To exchange data without losing formatting or anything else.
     result = JSON.parse(result);

     /* The we use the name of our PHP array key as a property 
        Here it is "response" (see PHP json_encode line)       */
     alert(result.response);
  }
}
/* Change this URL for the PHP filename. we use the GET method to send data. */
/* You should always use the POST method when sending sensitive data */
xmlhttp.open("GET","getUserClicks.php?clicks="+count+"&username="+username,true);
xmlhttp.send();

PHP (here it is the file named getUserClicks.php )

<?php
if(!isset($_GET['username']) || !isset($_GET['clicks']))
    die("Error");

$username = $_GET['username'];
$jsClicks = $_GET['clicks'];
$phpClicks = null;

#I am using the mysqli class to execute the query since mysql is deprecated in PHP5.
$data = mysqli_query("SELECT clicks FROM customerdetails WHERE customer_username='$username'"); 

while($row = mysqli_fetch_array($data))
{
    $phpClicks = $row['clicks'];
}

#If your "IF" only contains one line, you don't need brackets.
#Otherwise they are needed.

if($phpClicks == null)
    die("Could not get the number of clicks of the desired username");

#This is the string PHP will send to Javascript.
$response = "Same number of clicks!";

#If phpClicks is different and has the same type as jsClicks...
if($phpClicks !== $jsClicks)
{
    $response = "Number of clicks changed!";
    if($jsClicks > $phpClicks)
    {
        #Updates the number of clicks the user has done.
        $mysqli_result = mysqli_query("UPDATE customerdetails SET clicks=$jsClicks WHERE customer_username='$username';"); 
    }
}

echo json_encode(array('response'=>$response));

?>

Be sure to make some research if you see functions or methods you have no idea what they do (eg.: isset).

Jeff Noel
  • 7,500
  • 4
  • 40
  • 66
  • Hi, Ghillied. Thanks for the suggestion. I had went through the tutorial of AJAX in w3schools. Can you please explain a little bit more in details how can i solve my problem with AJAX? I'm sorry because i am quite weak in programming. yet, i am trying my best to learn. By using AJAX, i should separate both javascript and php file ? Then, run the php file, use AJAX to call the function in javascript ? like : xmlhttp.open("GET","click.html",true); ? Then how do i only retrieve the "clicks" in javascript and compare with data in my database ? – CK Tan Jan 07 '13 at 17:17
  • I am working on an example for you. I'll edit my post as soon as it is done. – Jeff Noel Jan 07 '13 at 18:12
  • thank you so much for that ~ I am trying my best to do too.. but i can't figure out where should i divide the parts. like which function in which .php or .html ~ *confused* – CK Tan Jan 07 '13 at 18:16
  • Please take a look at my edit. I hope it'll help you in some way. I suggest you to use W3Schools a lot, and Google always helps ;-). – Jeff Noel Jan 07 '13 at 18:57
  • May i know what is the different between mysql and mysqli ? Oops ~ just saw your //comment ~ thanks for that ~ – CK Tan Jan 07 '13 at 19:04
  • what is the function of echo json_encode(array('response'=>$response)); – CK Tan Jan 07 '13 at 19:07
  • As said in the comments, JSON is a language which is used when sending data from PHP to Javascript. We need to encode our regular PHP array into a JSON array. Usualy, a PHP array is made this way: [0]=>["a"],[1]=>["b"] ... we gave PHP our own arra key, which works like this: [response]=>["our $response string variable"]. This way we can read it in Javascript like this: `result.response` which contains the $response value. Sadly, StackOverflow is no the best place to learn basic stuff. I suggest that you try to find some tutorials online or seek through already answered questions here. – Jeff Noel Jan 07 '13 at 19:39