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>
1

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

Comments

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).

7 Comments

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 ?
I am working on an example for you. I'll edit my post as soon as it is done.
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
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 ;-).
May i know what is the different between mysql and mysqli ? Oops ~ just saw your //comment ~ thanks for that ~
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.