Click counter on a div using php - php

I know nothing about javascript, but I'm using javascript in a couple places on my site to make it look a little nicer. One of these places is where when a user clicks a div, it can open a nice looking popup with more information. However, I also want to save the number of clicks a div has.
I know how I could do this with php, and I've managed to find some javascript code that could increment a variable, but I don't think those two can be combined unless the js saves the var as a cookie, which I think could have some security flaws if I'm then reading the js variable back into the database.
The javascript code I have is
/*Click counter*/
var clicks = 0;
function count()
{
document.getElementById( "cc" ).value = ++clicks;
}
and I'm not sure of where to start with the php since I don't know the javascript. But querying the database to increment the column that stores the number of clicks will be simple. I just don't know how to tell php that a click has been made using javascript. I don't think it can be done in php, unless the link goes to a php file which handles all of this first and then redirects, which won't work in this case since the popup wouldn't be loaded in the new page.
Any ideas or pseudo-code to help?

You should use AJAX to update the server database if you want to keep the counter up to date on the server side.
Based on this tutorial, here's a quick example:
mydiv.phtml:
<?php $_GET['id']=isset($_GET['id'])?$_GET['id']:1; include 'count.php'; ?>
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
var clickerid = <?php echo $_GET['id'] ?>; //counter id allows easy implementation of other counters if desired
var clicks = <?php echo $clicks ?>;
var clickLock = false;
var maxClickRate = 1000; //maximum click rate in ms, so the server won't choke
//Browser Support Code
function count(){
if (clickLock) {
alert('you\'re clicking too fast!');
return;
}
clickLock=true;
setTimeout('clickLock=false;',maxClickRate);
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
}catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
}catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
}catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data
// sent from the server and will update
// div section in the same page.
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
document.getElementById('cc').innerHTML = ++clicks;
}
}
// Now pass clicks value to the
// server script.
var queryString = "?id=" + clickerid + "&update=true";
ajaxRequest.open("GET", "count.php" +
queryString, true);
ajaxRequest.send(null);
}
//-->
</script>
<div onclick='count()'>
<form name='myForm'>
<input type='button' value='clickOnDiv'/>
</form>
</div>
Clicks so far: <span id='cc'><?php echo $clicks; ?></span>
</body>
</html>
count.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost;dbname=test', 'user', 'password');
if (!isset($_GET['update'])){
$stmt = $dbh->prepare('SELECT count
FROM clicks
WHERE id = :clickerid');
$stmt->bindValue(':clickerid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$clicks = $result['count'];
} else {
$stmt = $dbh->prepare('UPDATE clicks
SET count = count + 1
WHERE id = :clickerid');
$stmt->bindValue(':clickerid', $_GET['id'], PDO::PARAM_INT);
$stmt->execute();
}
$dbh = null;
} catch (PDOException $e) {
print "PDO Exception.";
die();
}
?>
set_database.php:
<?php
try {
$dbh = new PDO('mysql:host=localhost', 'user', 'password');
$dbh->query('CREATE DATABASE test;');
$dbh->query('CREATE TABLE test.clicks (id INT KEY, count INT);');
$dbh->query('INSERT INTO test.clicks VALUES (1,0);');
$dbh = null;
} catch (PDOException $e) {
print "PDO Exception.";
die();
}
?>

Related

Google Maps API V3 not showing map

Okay so I have a PHP script which handles file uploads, KML files specifically, extracts the center point and the location of the uploaded file, saves these details in text files, and then loads another page via "header". This other page then uses AJAX calls to set variable names as gathered from the text files, for the location of the KML file and the center point, in order to call the Google Maps API to show the KML layer upon a map.
That is what is supposed to happen, but instead nothing appears. I browse for my KML file, hit the upload button, and a blank page is shown. When I check my server, the file as been uploaded and the relevant details written into their respective text files, so obviously something is going wrong when I try to call the Google Maps API.
PHP upload and file info saving:
<?php
//Check that we have a file
if((!empty($_FILES["UploadedFile"])) && ($_FILES['UploadedFile']['error'] == 0)) {
//Check if the file is JPEG image and it's size is less than 3Mb
$filename = basename($_FILES['UploadedFile']['name']);
$ext = substr($filename, strrpos($filename, '.') + 1);
if (($ext == "kml") && ($_FILES["UploadedFile"]["size"] < 3145728)) {
//Determine the path to which we want to save this file
$newname = dirname(__FILE__).'/kml/'.$filename;
//Check if the file with the same name is already exists on the server
if (!file_exists($newname)) {
//Attempt to move the uploaded file to it's new place
if ((move_uploaded_file($_FILES['UploadedFile']['tmp_name'],$newname))) {
findCenter($newname);
saveName($newname);
} else {
echo "Error: A problem occurred during file upload!";
}
} else {
echo "Error: File ".$_FILES["UploadedFile"]["name"]." already exists";
}
} else {
echo "Error: Only .kml files under 3Mb are accepted for upload";
}
} else {
echo "Error: No file uploaded";
}
function findCenter($file) {
$kmlContent = file_get_contents($file);
$startName = "#sh_green-circle";
$endName = "#sh_red-circle";
$startCoords = getCoords($kmlContent, $startName);
$endCoords = getCoords($kmlContent, $endName);
$startLat = substr($startCoords, strrpos($startCoords, ',') +1);
$startLong = substr($startCoords, 0, strrpos($startCoords, ','));
$endLat = substr($endCoords, strrpos($endCoords, ',') +1);
$endLong = substr($endCoords, 0, strrpos($endCoords, ','));
$midLat = ($startLat+$endLat)/2;
$midLong = ($startLong+$endLong)/2;
$midCoord = "$midLat,$midLong";
$saveCenter = "kmlcenter.txt";
$fh = fopen($saveCenter, 'w') or die ("Can't create file");
$stringData = $midCoord;
fwrite($fh, $stringData);
fclose($fh);
}
function getCoords($kml, $name) {
$startSearch = strpos($kml, $name);
$midSearch = strpos($kml, "<coordinates>", $startSearch+1);
$endSearch = strpos($kml, "</coordinates>", $midSearch+1);
$longlat = substr($kml, $midSearch+13, $endSearch-($midSearch+13));
return $longlat;
}
function saveName($filename) {
$saveFile = "kmlfilename.txt";
$fh = fopen($saveFile, 'w') or die("Can't create file");
$stringData = "$filename";
fwrite($fh, $stringData);
fclose($fh);
header("Location: initgmaps.html");
}
?>
Map intitialisation:
<script type="text/javascript" src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB8P7CzxiwQFf-RdK9QVRpH9se8AsMSsjEsensor=false"></script>
<script type="text/javascript">
function initialize() {
var kmlName = getName()
var kmlCoords = getCoords()
var mapcenter = new google.maps.LatLng(kmlCoords);
var myOptions = {
zoom: 11,
center: mapcenter,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
var map = new google.maps.Map(document.getElementById("infoArea"), myOptions);
var kmlLayer = new google.maps.KmlLayer(kmlName);
kmlLayer.setMap(map);
}
</script>
Relevant AJAX functions:
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function getName(){
var ajaxRequest; // The variable that makes Ajax possible!
var kmlName;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
kmlName = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "kmlfilename.txt", false);
ajaxRequest.send(null);
}
//-->
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function getCoords(){
var ajaxRequest; // The variable that makes Ajax possible!
var kmlCoords;
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser does not support AJAX.");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4 && ajaxRequest.status == 200){
kmlCoords = ajaxRequest.responseText;
}
}
ajaxRequest.open("GET", "kmlcenter.txt", false);
ajaxRequest.send(null);
}
//-->
And of course in the body of initgmaps.html I have:
onload="initialize()"
infoArea is the ID for my inline frame.
Can anyone see why it doesn't load? I'm completely and utterly new to web development, learning as I go, so sorry if the code is terrible and I'm sure I've made some obvious errors. Many thanks.
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyB8P7CzxiwQFf-RdK9QVRpH9se8AsMSsjEsensor=false"></script>
You have missed an ampersand here... Should be:
<script type="text/javascript"
src="https://maps.googleapis.com/maps/api/js?key=[[YOUR-GMAPS-KEY]]&sensor=false"></script>
(Where [[YOUR-GMAPS-KEY]] is your Google Maps Key - "AIzaSyB8P7CzxiwQFf-RdK9QV...".)
Try adding an ampersand '&' after your key and before the sensor=false parameter.
Additionally
var kmlCoords = getCoords()
is javascript, but function getCoords() is PHP. Javascript cannot execute a PHP function.
the error might be caused by not following this format:
src="https://maps.googleapis.com/maps/api/js?key=YOUR_API_KEY"
see, after "YOUR_API_KEY" there shouldn't be "sensor=false".
try it. hope it works.

Front end mysql view, delete entry with checkbox?

I'm building off of a question I had asked and resolved earlier: front end mysql, deleting a row
Basically, I've got a front end where users can view a DB. Instead of having a delete button next to each row, I'd like to have a checkboxes that can be selected for multiple rows. Then, the user only clicks a single delete button and all the selected rows are removed. I don't know much php and mysql at all, so I'm not sure how to approach the code that I already have.
Currently, the onclick calls a delete function. Can anyone help?
I've got a php file that outputs the html for the mysql data into a long strong, the part I need to change is:
$display_string .= "<td class='blank'><input type=\"button\" VALUE=\"Delete\" onclick='delFunction(" . $row['ID'] . ")' ></td>";
Next my delete function:
function delFunction(ID){
// confirm delete
if (!confirm(\"Are you sure you want to delete?\")) return false;
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject(\"Msxml2.XMLHTTP\");
} catch (e) {
try{
ajaxRequest = new ActiveXObject(\"Microsoft.XMLHTTP\");
} catch (e){
// Something went wrong
alert(\"Your browser broke!\");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
var ajaxDisplay = document.getElementById('ajaxDiv');
ajaxDisplay.innerHTML = ajaxRequest.responseText;
}
}
var queryString = \"?ID=\" + ID
ajaxRequest.open(\"GET\", \"delete_row.php\" + queryString, true);
ajaxRequest.send(null);
}
To my understanding of your problem, I am posting some codes for both front and back ends
Front-End Sample Code
<body>
<form action="delete.php" method="post">
<input type="checkbox" name="del_chk[]">Item1
<input type="checkbox" name="del_chk[]">Item2
<input type="checkbox" name="del_chk[]">Item3
<input type="checkbox" name="del_chk[]">Item4
.
.
<input type="submit">
</form>
................
Your back-end code would now be...
<?php
if(isset($_POST['del_chk'])){
$chkbox=$_POST['del_chk'];
foreach($chkbox as $key=>$value) {
//Now you can get your value and use it in mysql delete statements
//for example
$del_query="DELETE FROM `yourtable` WHERE `pri_key`=$value;";
if(mysql_query($del_query)) {
echo "Successful Deletion of: ".$value;
}
else
{
echo "Unsuccessful Deletion of: ".$value;
}
} //end foreach
}
?>
I don't know much of ajax. but you can use ajax to call this page..

Why is this AJAX function not working properly?

I have written a simple application that displays a list of candidates for a job, then, upon clicking a hire button, should alter a database to reflect the newly hired candidate and display the rest as unhired. However, the function is not working properly. The problem I am having is the AJAX function never seems to provide a response, and I cannot figure out why. The database is also not getting updated. My files are below.
The line document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>"; is updating a div at the bottom of my html page, showing that the the readyState is 4 and the status is 200, which should mean that the AJAX function returned properly, but the echo'd response is not being displayed. Even when I remove all code from the new_hire.php file and simply make the file echo "hello";, nothing is returned in the responseText.
resumes.php:
<html>
<head>
<script type="text/javascript">
function new_hire(name){
var xmlhttp;
if (window.XMLHttpRequest){
xmlhttp=new XMLHttpRequest();
}
else{
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function(){
document.getElementById("errors").innerHTML+=xmlhttp.readyState+" "+xmlhttp.status+"<br>";
//this line, when removed, does not change anything. I left it in for debugging purposes.
document.getElementById("errors").innerHTML+=xmlhttp.responseText;
if (xmlhttp.readyState=4 && xmlhttp.status=200){
var others = xmlhttp.responseText.split("|");
for (i=0;i<others.length;i++){
tag = others[i].replace(" ","_");
document.getElementById(tag).innerHTML="";
}
}
}
xmlhttp.open("POST","new_hire.php",true);
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
xmlhttp.send("hiree="+name.replace(" ","%20")+"&position=Salespeople");
var name_tag = name.replace(" ","_");
document.getElementById(name_tag).innerHTML="(Current Employee)<br>";
}
</script>
</head>
...
</html>
new_hire.php (AJAX response file):
<?php
$hiree = $_POST['hiree'];
$pos = $_POST['position'];
$con = mysql_connect("host.name","user","pass") or die('Could not connect: ' . mysql_error());
mysql_select_db("dbname",$con);
$clear = mysql_query("UPDATE $pos SET employed=false WHERE 1=1;");
mysql_fetch_array($clear);
$reset = mysql_query("UPDATE $pos SET employed=true WHERE Name='$hiree';");
mysql_fetch_array($reset);
$people = mysql_query("SELECT Name FROM $pos WHERE employed=false;");
$array = array();
while ($row = mysql_fetch_array($people)){
array_push($array,$row['Name']);
}
mysql_close($con);
$response = join("|",$array);
echo $response;
?>
Please note that your if statement is not using the comparison operator == but rather the assignment operator = so you are using: if (xmlhttp.readyState=4 && xmlhttp.status=200) instead of if (xmlhttp.readyState==4 && xmlhttp.status==200)

random quote generator with php, ajax and mysql

i've tried using this code and this to make a random quote generator, but it doesn't display anything. my questions are:
what is wrong with my code?
in the above tut, the quote is generated on a button click, i'd like
a random quote to be displayed every
30 mins automatically. how do i do
this?
////////////////////////
quote.html:
<!DOCTYPE html>
<script src="ajax.js" type="text/javascript"></script>
<body>
<!–create the div for the quotes land–>
<div id="quote"><strong>this</strong></div>
<div><a style="cursor:pointer" onclick="run_query();">Next quote …</a></div>
</body>
</html>
/////////////////////
quote.php:
<?php
include 'config.php';
// 'text' is the name of your table that contains
// the information you want to pull from
$rowcount = mysql_query("select count(*) as rows from quotes");
// Gets the total number of items pulled from database.
while ($row = mysql_fetch_assoc($rowcount))
{
$max = $row["rows"];
}
// Selects an item's index at random
$rand = rand(1,$max)-1;
$result = mysql_query("select * from quotes limit $rand, 1");
$row = mysql_fetch_array($result);
$randomOutput = $row['storedText'];
echo '<p>' . $randomOutput . '</p>';
////////////
ajax.js:
var xmlHttp
function run_query() {
xmlHttp=GetXmlHttpObject();
if (xmlHttp==null) {
alert ("This browser does not support HTTP Request");
return;
} // end if
var url="quote.php";
xmlHttp.onreadystatechange=stateChanged;
xmlHttp.open("GET",url,true);
xmlHttp.send(null);
} //end function
function stateChanged(){
if (xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
document.getElementById("quote").innerHTML=xmlHttp.responseText;
} //end if
} //end function
function GetXmlHttpObject() {
var xmlHttp=null;
try {
// For these browsers: Firefox, Opera 8.0+, Safari
xmlHttp=new XMLHttpRequest();
}catch (e){
//For Internet Explorer
try{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
} //end function
Try to print the values for $max,$rand and $result. You can use print_r to get more info from the php page.
Run the quote.php on browser to see if you get an output.
Then get to ajax to debug.
You can use a timer in ajax to automate your requests for every 30 mins or so. use javascript's settimeout function for this.
HTH

Ajax Returns Random Values?

I am working on a simple AJAX page. when the page loads, it should take the result from the PHP page and display it in the text box. If the result is "1" (which it should be), then it should pop up an alert saying "Ready."
Main page's code (t1_wait.php):
<html><head><title>Waiting...</title></head><body>
<script type="text/javascript">
function update(id)
{
var xmlhttp;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
}else if (window.ActiveXObject){
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}else{
alert("Your browser does not support XMLHTTP!");
}
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4){
if(xmlhttp.responseText=="1")
alert("Ready!");
}
document.myForm.status.value=xmlhttp.responseText;
}
}
var requesturl = "t1_checkMatch.php?id="+id;
xmlhttp.open("GET",requesturl,true);
xmlhttp.send(null);
// delay for 1 sec
var date = new Date();
var curDate = null;
do { curDate = new Date(); }
while(curDate-date < 1000);
}
<?php
echo "update(".$_GET['id'].");";
?>
</script>
<form name="myForm">
Status: <input type="text" name="status" />
</form>
</body></html>
The PHP page being called out to (t1_checkMatch.php) (all db info replaced with *****):
<?php
$db_user = "*****";
$db_pass = "*****";
$db_name = "*****";
mysql_connect(localhost,$db_user,$db_pass);
#mysql_select_db($db_name) or die("Unable to select database");
$match_id = $_GET['id'];
$match_info = mysql_query("SELECT * FROM ***** WHERE id=".$match_id);
if(mysql_result($match_info,0,"usr2")==-1){
echo "1";
}else{
echo "0";
}
?>
When I go to the t1_wait.php?id=16 (the main page passing id=16 via GET), it should send a request to t1_checkMatch.php?id=16, which returns (yes, I checked) 1. This should trigger an alert saying "Ready" and cause 1 to appear in the text box, but neither of these things happen. The text box is blank.
What's wrong? Thanks!
I believe the problem you are running into is due to a typo
xmlhttp.responceText
Really should be
xmlhttp.responseText
-- Update
It also appears that you are missing a {:
if(xmlhttp.responseText=="1")
alert("Ready!");
}
Should be
if(xmlhttp.responseText=="1"){
alert("Ready!");
}
You have a spelling mistake:
if(xmlhttp.responceText=="1")
should be:
if(xmlhttp.responseText=="1")
(you spelled response incorrectly)
Ok. I figured it out, but I don't know what I did. I did have a typo, but that isn't the problem. The PHP code is the same, here is the main page code:
<html>
<body>
<script language="javascript" type="text/javascript">
<!--
//Browser Support Code
function update(id){
var ajaxRequest; // The variable that makes Ajax possible!
try{
// Opera 8.0+, Firefox, Safari
ajaxRequest = new XMLHttpRequest();
} catch (e){
// Internet Explorer Browsers
try{
ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try{
ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e){
// Something went wrong
alert("Your browser broke!");
return false;
}
}
}
// Create a function that will receive data sent from the server
ajaxRequest.onreadystatechange = function(){
if(ajaxRequest.readyState == 4){
if(ajaxRequest.responseText.indexOf("1")!=-1){
document.myForm.status.value = "Ready!";
window.location = "t1_game.php?id="+id;
}else{
document.myForm.status.value = "Waiting..."
update(id);
}
}
}
ajaxRequest.open("GET", "t1_checkMatch.php?id="+id, true);
ajaxRequest.send(null);
}
<?php
echo "update(".$_GET["id"].");"
?>
//-->
</script>
<form name='myForm'>
Status: <input type='text' name='status' />
</form>
</body>
</html>

Categories