Store jQuery click count in a cookie, and then echo it. - php

I'm trying to use jQuery to count clicks, store them in a cookie and then echo them back out.
I've found some code online that allows me to do it, but I dont seem to be able to make it work. It's creating the cookie file and storing '0' in it, but it does not update on clicking of links. Any guidance as to whats going wrong with this code would be great. :
clickCount.js
jQuery(function(){
$("a").click(function{
var cookiename = 'linkcounter';
if($.cookie(cookiename) == null){
$.cookie(cookiename, 0);
}
$.cookie(cookiename, $.cookie(cookiename)+1);
});
});
index.php
<?php
session_start();
$counter_file = 'counter';
if(!file_exists($counter_file)){
file_put_contents($counter_file, 0);
}
$counts = (int)file_get_contents($counter_file);
file_put_contents($counter_file, $counts++);
// you can use $counts if you want to display it on the page.
?><!DOCTYPE html>
<html>
<head>
<title>Link Click Counter Test</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript" src="jquery.cookie.js"></script>
<script type="text/javascript" src="countdetect.js"></script>
</head>
<body>
<br />
<br />
Link clicks: <?php echo $counts; ?>
</body>
</html>

In you PHP code, you're not storing the click count into a cookie, but into a file.
You either have to update the counter file by by making an AJAX request from your JavaScript to your server, or actually write a cookie within your PHP file:
<?php
$cookieName = 'linkcounter';
$count = isset($_COOKIE[$cookieName]) ? (int)$_COOKIE[$cookieName] : 0;
$count++;
setcookie($cookieName, $count);
?>
Link clicks: <?=$count?>
Make sure you use the same cookie name in both JavaScript and PHP.

Related

interaction between jquery and php using GET

I want to write a web page and use jquery to GET a small amount of data from php at the server, but in the same file, when i click a button. I want to send ?nm=bill and answer with 'bob'. i press the button but it doesn't seem to arrive at the server. I get the contents of the file i am sending the query to. I clear the browser, firefox, history before i press the button. Here is the code.
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
$("#btn").click(function(){
console.log("btn pressed");
$.get("a_foo.php?nm=bill", function(data, status){
alert("Data:\n" + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p>
<body>
<?php
if ($_SERVER["REQUEST_METHOD"] == "GET"){
var_dump($_SERVER["REQUEST_METHOD"]);
if ($_SERVER['QUERY_STRING']) {
echo "bob";
}
}
?>
</body>
</html>
but in the same file
So all of the code shown is in one file? If that's the case then any request to that file is going to receive the entire response.
I get the contents of the file i am sending the query to.
That's expected behavior. The very first thing this file does is emit all of the HTML at the start. Then it executes some PHP and conditionally emits a single value at the end.
Putting these things into separate files would be the ideal approach. One file is the UI, the other file is the service that handles the AJAX request and returns just the expected data.
But if you really want them to be in the same file then you'd need to conditionally return all of that HTML. Since the only difference between the requests at this time is whether or not a query string is present then your whole PHP file would look something like:
<?php
if ($_SERVER['QUERY_STRING']) {
echo "bob";
} else {
/>
<!-- ALL of your other HTML goes here -->
<?php
}
?>
As you can probably imagine, this structure gets pretty ugly and difficult to maintain pretty fast. Which is why the preferred approach is to separate these things into their own files. Each PHP file would do just the one thing it needs to do, rather than having one big PHP file which conditionally does multiple different things.
The current target of request is a_foo.php i fix it and show bob if the get nm is bill else show html
<?php
$_nm = $_GET["nm"];
if($_nm == "bill"){
echo "bob";
}
else
{
?>
<!DOCTYPE html >
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
// --- embed the call in btn by id ---
$(document).ready(function(){
$("#btn").click(function(){
console.log("btn pressed");
$.get("?nm=bill", function(data, status){
alert("Data:\n" + data + "\nStatus: " + status);
});
});
});
</script>
</head>
<body>
<?php
$rsp = "7 come 11";
?>
<button id="btn">Send</button>
<p id="rch"><?php echo $rsp; ?> </p>
<body>
</body>
</html>
<?php
}
?>

Read Cookie Data from PHP in Javascript

I have a PHP file that contains both the PHP Code and the JQuery Code. My motive is to set cookies as and when the PHP code is executing and read the cookies set by PHP in the JQuery part of the code and make some decision. But I'm not able to do that. What would be the best way for me to achieve this.
I'm new to PHP any help would be great.
<?php>
if(isset($_POST['StartProcess'])){
$Process_step = 1;
setcookie("MyCookie", $Process_step); sleep(30);
$Process_step = 2;
setcookie("MyCookie", $Process_step); sleep(30);}
<?>
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
window.setInterval(function(){
var abc = document.cookie.split(";").map(function(el){ return el.split("="); }).reduce(function(prev,cur){ prev[cur[0]] = cur[1];return prev },{});
console.log(abc["MyCookie"]);
if(Step == 1){ do something;}else if(Step == 1){ do something else;}
})
})</script>
<head>
<body></body>
</html>
If I understand your question correctly, you would like to use PHP session value on the JQuery.
You can print the variable of PHP in the JQuery line. You can do it like this
var myvalue = "<?PHP $phpvarname ?>"
or you can use PHP session and assign it on the var.

onbeforeunload doesn't seem to always be trigerred

Here's a minimum example -
index.php
<?php
$count = file_get_contents("count.txt") + 0;
file_put_contents("$count.txt [loaded]", '');
file_put_contents("count.txt", $count + 1);
?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<script src="jquery-1.10.2.min.js"></script>
</head>
<body>
<main>
<p> hi there </p>
</main>
<script type="text/javascript">
var id = "<?php echo $count; ?>";
</script>
<script src="script.js"></script>
</body>
</html>
script.js
$(document).ready(function ()
{
$(window).bind('beforeunload', function () {
$.post("unloader.php", { id : id });
});
});
unloader.php
<?php
file_put_contents("$_POST[id] [unloaded]", '');
When I open the webpage, a file is created with the count number as its name.
When I close the tab jquery requests unloader.php which is just a standalone script that creates a file with the count number as its name too.
Sometimes it works, sometimes it doesn't.
I mean the opening file is always created. But sometimes the file which has to be created on closing is not made.
Any idea where the issue occured ?
You can't (reliably) make AJAX calls when unloading the page. Because it's being unloaded, anything still in progress will be dropped.
If the browser's fast enough with the AJAX call (or the server's slow enough in responding to the new page load) then you should see a result, but it is not at all reliable.

jquery autocomplete sends empty get value to php

i am very new to jquery n javascript. I am trying to make an autocomplete feature. I am using a sample code from a diff page to do this. but the 'term' it passes to the php page is empty. so the autocomplete doesnt work. I dont understand why, can someone take a look? I didnt change the labels but i am just trying to test it to see if it works. the issue is with the php page, the request 'term' is empty.
<head>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script>
$(function() {
$( "#txtLanguage" ).autocomplete({
source: "source.php",
minLength: 1 // how many character when typing to display auto complete
});
});
</script>
</head>
<body>
<label for="Language">Language: </label>
<input id="txtLanguage" class="txtLanguage"/>
</div>
</body>
</html>
<?php
include 'dbconnect.php';
$q=$_REQUEST['term'];
echo $q;
$return = array();
$stat="SELECT email FROM users WHERE email LIKE '$q'";
$query = sqlsrv_query($conn,$stat);
while ($row = sqlsrv_fetch_array($query,SQLSRV_FETCH_ASSOC)) {
array_push($return,array('label'=>$row['email'],'value'=>$row['email']));
}
echo(json_encode($return));
?>
I think you need this:
$stat="SELECT `email` FROM `users` WHERE `email` LIKE '$q%'";
You forgot for % symbol and LIKE without % is equal to email = '$q'
Are you sure, the file path is correct? Is there any javascript error in the console?
Try console $( "#txtLanguage" ).
Remove source.php and add an array
Hope this helps you.
Use $_GET['term'] instead of $_REQUEST['term']

How to refresh a div in which php code is executing

a group images are calling in a div and there we have given an option to rotate images if required.
Actually the image is rotating but it is not showing in the page( without doing 2 or 3 manual page refresh).
I have added
<meta HTTP-EQUIV="Pragma" content="no-cache"/>
<meta HTTP-EQUIV="Cache-Control" content="no-cache"/>
at head
also done
if(isset($_GET['re'])=='re')
{
?>
<script language="JavaScript" type="text/javascript">
var reloaded = false;
var loc=""+document.location;
loc = loc.indexOf("?reloaded=")!=-1?loc.substring(loc.indexOf("?reloaded=")+10,loc.length):"";
loc = loc.indexOf("&")!=-1?loc.substring(0,loc.indexOf("&")):loc;
reloaded = loc!=""?(loc=="true"):reloaded;
function reloadOnceOnly() {
if (!reloaded)
window.location.replace(window.location+"?reloaded=true");
}
reloadOnceOnly(); //You can call this via the body tag if desired
</script>
<?php
}
But it is not showing the new rotated or changed image without another manual refresh.
Could you please help me on this?
Why not
<script>
function rotate(imgId,direction) {
var img = document.getElementById(imgId);
img.src=img.src.split("rotation=")[0]+"rotation="+direction+"&rnd="+new Date().getTime();
return false;
}
</script>
<img id="image1" src="getimage.php?name=image1&rotation=0" /><br />
Reset
90°
180°
270°
If I understand you correctly, you're trying to use a PHP to code to refresh the webpage? However, the issue here is that once the PHP is output to the client, you can't have control over it already. The best thing to do in this context is to use JavaScript to do the refresh for you. Hope it helps :)
Hi Merlin, you might want to use a simpler logic like this:
<script type="text/javascript">
var reloaded = false;
var loc=""+document.location;
loc = loc.indexOf("?reloaded=");
if (loc == -1){
window.location.replace(window.location+"?reloaded=true");
}
</script>
Optionally you might want to pack it into a function for your use. Hope it helps (:

Categories