I am counting the clicks on anchors and store the number of clicks in a .txt file.
When click on an anchor, the number increases by 1.
I am not using a user management system, so to prevent multiple clicks on an anchor by a user, i need to store a cookie.
But i do have multiple anchors. If a user clicks on anchor 1, the number of click events on anchor 1 increases by 1. He should not have the possibility to click a second time on anchor 1, at least: it should not increase by 1 anymore.
But for that user, he still must be able to click on anchor 2 and anchor 3 and it should increase with 1. And after this, also these anchors should not increase by 1 anymore when user clicks on it.
How can i achieve this?
This is my html;
<?php
$clickcount = explode("\n", file_get_contents('counter.txt'));
foreach($clickcount as $line){
$tmp = explode('||', $line);
$count[trim($tmp[0])] = trim($tmp[1]);
}
?>
Like
<span class="click-count"><?php echo $count['count1'];?></span> likes.
Like
<span class="click-count"><?php echo $count['count2'];?></span> likes.
Like
<span class="click-count"><?php echo $count['count3'];?></span> likes.
The js:
$(document).on('click', '.click-trigger', function()
{
var data = {'id':$(this).attr('data-click-id')};
var count = $(this).next(".click-count");
$.ajax({
type : 'POST',
url : 'counter.php',
data : data,
success : function(data)
{
$(".click-count").fadeIn(500).show(function()
{
count.html(data);
});
}
});
return false;
});
And this is file counter.php
$file = 'counter.txt'; // path to text file that stores counts
$fh = fopen($file, 'r+');
$id = $_REQUEST['id']; // posted from page
$lines = '';
while(!feof($fh)){
$line = explode('||', fgets($fh));
$item = trim($line[0]);
$num = trim($line[1]);
if(!empty($item)){
if($item == $id){
$num++; // increment count by 1
echo $num;
}
$lines .= "$item||$num\r\n";
}
}
file_put_contents($file, $lines);
fclose($fh);
The file counter.txt looks like this:
count1||36
count2||124
count3||12
You can use serialize on an array of item numbers when setting the cookie value from php, and unserialize when reading the cookie. You will get an array of integers and can check with in_array whether the user has already clicked the link.
Related
The main problem is every time the users will click the heart button for likes, they can spam the like button and the likes will also increase every time you click the like button.
here's my php code:
`
<?php
if(isset($_POST['how'])){
session_start();
$user_id=$_SESSION['userId'];
$post_id=$_POST['data'];
$con = new mysqli("localhost","root","","tattoo_db");
$sql1="SELECT `design_id`, `count` FROM `works` WHERE design_id='$user_id' and
count='$post_id'";
$res=$con->query($sql1);
if($res->num_rows == 0){
$sql2="UPDATE `works` SET `count`=count+1 WHERE design_id='$post_id'";
if($con->query($sql2)){
$sql3="INSERT INTO `works`(`design_id`, `count`) VALUES ('$user_id','$post_id)";
if($con->query($sql3)){
echo "liked";
}
}
}else if($res->num_rows==1){
$sql2="UPDATE `works` SET `count`=count-1 WHERE design_id='$post_id'";
if($con->query($sql2)){
$sql3="DELETE FROM `works` WHERE design_id='$user_id' and count='$post_id'";
if($con->query($sql3)){
echo "disliked";
}
}
}
}
?>
`
and this is my javascript code:
`
$(document).ready(function(){
$(".like").click(function(){
var design_id=$(this).attr("title");
var i=$(this).children(".like_icon").attr("src");
if(i=="admin/works/heart.svg"){
$(this).children(".like_icon").attr("src","admin/works/red-heart.svg");
$(this).children("span").text("liked");
}else if(i=="admin/works/red-heart.svg"){
$(this).children(".like_icon").attr("src","admin/works/heart.svg");
$(this).children("span").text("unliked");
}
$.post("header/get.php",{data:design_id,how:'c'});
});
});
`
I want to limit the users to one per like to prevent multiple likes from every users when they click the like button.
I have about 60 landing pages that use different phone numbers on them. I am using a combination of WordPress and Advanced Custom Fields to place the phone numbers on their respective pages.
I am being asked to show a <div> based on the landing page URL that will not only show the phone number assigned to that page, but, keep showing the <div> (and phone number) regardless of what page the user navigates to on the website.
I have found little to no support on how to make the <div> remain visible throughout the entire session until the user closes the window.
I am thinking that this will somehow revolve around a cookie and Dynamic Number Insertion but I have no real progress to speak of. Should this be done using PHP or JS? Does a plugin exist that would allow for this on WordPress? I'm open to all suggestions.
Please try this code. Like #John C mentioned, WP Engine doesn't recommend Cookie nor PHP Session for the sake of performance and security. This is pure JavaScript code, and I think this will solve your problem.
Code in your Post/Page template file:
<div id="phone-number"></div>
<?php if( get_field('phone_number') ): ?>
<script type="text/javascript">
let phone_number = "<?php the_field('phone_number'); ?>";
</script>
<?php endif; ?>
Code in your theme JavaScript file:
<script type="text/javascript">
// in the case of the div data is persistent on the same site
// let storage = localStorage;
// in the case of the div data is persistent in the same tab, but not in new tab
let storage = sessionStorage;
let key = "phone_number"; // storage key
var global_phone_number = storage.getItem(key);
// check if storage data is set before
if (null === global_phone_number) {
// if not set the data on page into storage
global_phone_number = phone_number ? phone_number : '';
storage.setItem(key, global_phone_number);
}
document.getElementById('phone-number').innerHTML = global_phone_number;
</script>
You should use PHP and capture the session.
(untested code warning)
add_action('wp_footer', 'dynamic_phone_div');
function dynamic_phone_div() {
session_start;
if(isset($_SESSION['phone_div']) ? $phone_div = $_SESSION['phone_div'] :
$phone_div = '';
if($phone_div != '') {
echo '<div class="that_div_thing">';
echo $phone_div;
echo '</div>';
} else {
$_SESSION['phone_div'] = 123456789;
echo '<div class="that_div_thing">';
echo '123456789';
echo '</div>';
}
}
This is only raw logic. I am not sure where your div is (header/footer/page) - depending on where it is you should either use a hook (header/footer) or code it into a template (page/post).
The session will be destroyed after the user closes the tab/window.
I would probably do this with client side session storage. Providing all pages open in the same tab, the value will remain for the session, then be removed.
PHP code (in your functions.php file?) would be something like this:
function phone_script() {
$params = array(
'phone_number' => null, // Insert logic for current number. Can stay null if this is running on a non-landing page
'is_landing_page' => false // Change to true/false based on is current page a landing one or not
);
$params = json_encode( $params );
echo <<< EOT
<script>
let settings = $params;
document.addEventListener("DOMContentLoaded", function() {
if( settings.is_landing_page ) {
window.sessionStorage.setItem( 'phone-number', settings.phone_number );
} else {
settings.phone_number = window.sessionStorage.getItem( 'phone-number' );
}
if( settings.phone_number ) {
let div = document.createElement('div');
div.classList.add('phone-div');
// or add inline style
// div.style.cssText = 'position:fixed'; //etc
// Some logic here to actually add the number and any other content to the div
div.innerHTML = `The Phone number is: ${settings.phone_number}`;
document.body.appendChild(div);
}
});
</script>
EOT;
}
add_action( 'wp_footer', 'phone_script');
Note that the EOT; line MUST have no leading or trailing spaces.
The above is untested.
I have a PHP page, where it has 12 individual form with individual form ID, and individual checkbox, dropdown etc. Like this pic:
Now, forms have Update Zone, which basically fetches, Name, Enable check or not, Time, Dim and sends it to PHP file for processing.
Code for 3 Zones
So, each form has hard coded URL LoopInfo.php?id=1 where id changes from 1 to 12, so the LoopInfo.php knows which Zone's update button is clicked and grabs post variables from that paticular zone
PHP Processing and updating XML
$id = $_GET['id'];
// echo "ID - ".$id.'<br>';
if($id > 0 && $id < 13)
{
// ZName - 1-12
// Zmode - 1-12
// ZTime - 1-12
// ZDim - 1-12
$radio = $_POST['radio'];
if($radio == 1)
{
$radio = 0;
}
// echo "Radio - ".$radio.'<br>';
$zn = "zname".$id;
$znam = $_POST["$zn"];
// echo "Name - ".$znam.'<br>';
$et = "EnTim".$id;
$entim = $_POST["$et"];
// echo "Timer - ".$entim.'<br>';
$ot = "OnTim".$id;
$ontim = $_POST["$ot"];
// echo "On Time - ".$ontim.'<br>';
$oft = "OfTim".$id;
$oftim = $_POST["$oft"];
// echo "Off Time - ".$oftim.'<br>';
$ed = "EnDim".$id;
$endim = $_POST["$ed"];
// echo "Dim - ".$endim.'<br>';
$d = "Dim".$id;
$dim = $_POST["$d"];
// echo "Dim Per - ".$dim.'<br>';
$bin = $radio.$endim."00000".$entim;
// echo "Binary - ".$bin.'<br>';
$loopval = bindec($bin);
// echo "Loop Val - ".$loopval.'<br>';
// print_r($_POST);
// die;
$hunza=simplexml_load_file('LoopInfo.xml');
if($hunza)
{
$zmode='Z'.$id.'Mode';
$hunza->$zmode=$loopval;
if($znam == '')
{
}
else
{
$name='Zname'.$id;
$hunza->$name=$znam;
}
if($entim == 1)
{
$ontime='Z'.$id.'TimeOn';
$hunza->$ontime=$ontim;
$oftime='Z'.$id.'TimeOff';
$hunza->$oftime=$oftim;
}
if($endim == 1)
{
$dimval='Z'.$id.'Dim';
$hunza->$dimval=$dim;
}
$hunza->asXML('LoopInfo.xml');
// echo "<script>console.log('File Updated' );</script>";
header("Location: index.php");
}
else
{
echo "Error Loading File";
echo "<script>console.log('Error Load File' );</script>";
}
}
So basically, each one is a form, when pressed on Update zone, grabs all form data, gives it to LoopInfo.php and LoopInfo.php updates those values to XML in their corresponding tags.
Target: What I am trying to achieve is that, is there any way, where I can update zone without the page being reloaded i.e., using Ajax Javascript. So Javascript grabs all value on update from form, creates Ajax request and post to the same PHP file for processing. I tried Googling "Javascript Ajax Multiple Form send data in one PHP" with no results. Is it possible to get a generic function which when invokes get the form Id and get to know this is ID 1 and created URL LoopInfo.php?id=1 and sends all form data along with this URL request.
The issue is cause of event propagation. Check your event - is it cause of multiple times form is submitting.
To avoid this place event.stopImmediatePropagation();
I am trying to delete a row of selected ID by passing a parameter into URL. let say, I have entryIDs 1 and 2, whenever I try to select and delete the content of entry 1, it successfully deletes the content of entryID 1 but the problem is when I choose to delete entryID 2 it still deletes entryID 1 instead of 2. I am thinking the content of a variable var row = '".$rows['Blog_ID']."'; doesn't change and only retains the value of entryID 1 even though I choose otherwise.
Here is what I tried so far..
<?php
include("../Connection.php");
$post_query="Select * from indexview order by Blog_ID Desc";
$postsql=mysqli_query($connect_db,$post_query) or die('Connection unsuccessful');
while($rows=mysqli_fetch_array($postsql,MYSQL_ASSOC)){
echo "<div id='posts'>";
echo" <select onchange = 'down(this.value)' id='downpng' name='downpng'>
<option value='void'></option>
<option value = 'edit'>Edit Blog</option>
<option value ='delete'>Delete</option>
</select>";
echo
"<script>
function down(temp) {
var row = ".$rows['Blog_ID'].";
var id = '".$_GET['id']."';
if(temp=='delete'){
var con = confirm('Are you sure?');
if(con){
window.location = 'google.php?entryID=' + row + '&id=' + id;
}else{
window.location = '../Blog/Blog.php?id=".$_GET['id']."';
}
}else{
window.location = '../Blog/edit.php';
}
}
</script>";
When I select <option value ='delete'>Delete</option> it is supposed to redirect me into deleteBlog.php page and delete the content of selected entryID.
deleteBlog.php code:
<?php
include("../Connection.php");
if(isset($_GET['entryID'])){
$user = $_GET['id'];
$entry = $_GET['entryID'];
mysqli_query($connect_db, "Delete from blog_tbl where Blog_ID=" .$entry);
header('Location: ../Blog/Blog.php?id='.$user);
}
?>
Any suggestions will be much appreciated. Thanks!
You need to do minimal php for this, especially when it comes to the javascript part. Just store the blog id (I am going to store it in the name of the select attribute) and extract via javascript. I am going to use jQuery to do the JS stuff.
<?php
# Include database
include("../Connection.php");
# Create a simple function that does not use id="downpng" (id values are
# supposed to be unique
function getOrderDropDown($con)
{
$query = "Select * from indexview order by Blog_ID Desc";
$postsql = mysqli_query($con,$query) or die('Connection unsuccessful');
$str = '';
while($rows=mysqli_fetch_array($postsql,MYSQL_ASSOC)){
$str .= "
<select name='downpng[".$rows['Blog_ID']."]' class='blog_select'>
<option value='void'></option>
<option value = 'edit'>Edit Blog</option>
<option value ='delete'>Delete</option>
</select>";
}
return $str;
}
# Write the selects to page
echo getOrderDropDown($connect_db);
?>
Javascript to extract the selection:
<script>
// I would only do php here, use a special chars, otherwise you will be easily hacked by user input
var id = <?php echo (!empty($_GET['id']))? '"'.htmlspecialchars($_GET['id'],ENT_QUOTES).'"' : 'false' ?>;
// On change of this class type
$('.blog_select').on('change',function(e) {
// Get the name (which contains the id)
var row = $(this).attr('name').replace(/[^0-9]/gi,'');
// This will be the action (delete, edit)
var action = $(this).val();
// On delete, assign the actions and send values
if(action == 'delete'){
var redirect;
var con = confirm('Are you sure?');
if(con){
redirect = 'google.php?entryID='+row+'&id='+id;
}else{
redirect = '../Blog/Blog.php?id='+id;
}
}else{
redirect = '../Blog/edit.php';
}
// Just do one redirect
window.location = redirect;
});
</script>
I have a column of buttons in a table, declared like this:
(file index.php)
echo '';
Then this script reads the data in the row of the button clicked and posts it to another php file:
<!-- scripts that gets the lecturer chosen to SHOW functionality-->
<script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
});
});
</script>
That file (show_lecturer.php) stores the data read in a table (keep_track) in the database:
(file show_lecturer.php)
<?php
ob_start(); //eliminates buffer collisions
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
?>
Then I create an empty dialogbox with jquery, to populate it with the data taken from the database:
(file index.php)
<!-- The following script generates the empty dialog box -->
<script src="/js/jquery.min.js"></script>
<link rel="stylesheet" href="/css/jquery-ui.css">
<script src="/js/jquery-ui.min.js"></script>
<script>
$(function() {
//show lecturer dialog
$("#show_dialog").dialog({autoOpen: false});
$(".show-button").on("click", function() {$("#show_dialog").dialog("open");});
});
</script>
Then these data are taken from the table keep_track and echoed in the above dialog:
(file index.php)
$name; $surname;
require_once('connect_db.php');
$firstname = pg_query(connect(), "SELECT name FROM keep_track");
while($row = pg_fetch_array($firstname)){ $name = $row['path']." ".$row['name']; }
$lastname = pg_query(connect(), "SELECT surname FROM keep_track");
while($row = pg_fetch_array($lastname)){ $surname = $row['path']." ".$row['name']; }
echo '<div id="show_dialog" class="ui-dialog-content ui-widget-content">';
echo $name."".$surname;
echo '</div>';
?>
So when I click the button of row x, a dialogbox opens with the data from the row x.
The only thing that is not working correctly is this:
The moment I click button x, it opens a dialog but displays a value, but not that of row x. However, when i see the database, the row x is stored there. The value in the checkbox is that of the button clicked before the latest refresh on the page. Its as if there is some mistake in my chain of calls or something (that I cant figure out, thats why Im asking).
To illustrate the data I get:
(Initially the table keep_track is empty)
Press button 1 -> row 1 stored, dialogbox has no content
Press button 2 -> row 2 stored, dialogbox has no content
Press button 3 -> row 3 stored, dialogbox has no content
Refresh page manually
Press button 4 -> row 4 stored, dialogbox has content from row 3
Press button 5 -> row 5 stored, dialogbox has content from row 3
Refresh page manually
Press button 6 -> row 6 stored, dialogbox has content from row 6
Press button 7 -> row 7 stored, dialogbox has content from row 3
I suggest you return your data from the POST via JSON. And please be aware that an AJAX Call is asynchronous. So you won't know when the reply is coming.
So you need to process your results using the ajax Success callback function.
</script>
$(document).ready(function(){
$(".show-button").click(function() {
var $row = $(this).closest("tr"); // Find the row
var names = $row.find(".name").text(); // Find the name
var surname = $row.find(".surname").text(); // Find the surname
do_post_and_show_info(names, surname);
});
});
function do_post_and_show_info(names, surname){
request= $.ajax({
type: "post",
cache: false,
url: "show_lecturer.php",
data: { x: names, y: surname} ,
dataType: "json",
});
request.done(function(json){
if (json.status =="ok"){
// DO YOUR THING!
Alert(json.data.names + " " + json.data.surnames);
}
else {
alert("Error! " + json.error + " : " + json.remarks);
}
});
request.fail(function(jqXHR, textStatus) {
alert( "Request failed: " + textStatus + ":" + jqXHR.responseJSON);
});
}//do_post_and_show_info
</script>
I usually return a datastructure like this in PHP (so in your show_lecturer.php)
<?
// get your data before this in the variable $data
// put your status "OK" or "ERROR" in $status
// put some error info in $extraInfo
// of course some processing is involved, but here's a simple example
require_once('connect_db.php');
$name = $_POST['x'];
$surname = $_POST['y'];
$result = pg_query(connect(), "INSERT INTO keep_track VALUES ('$name', '$surname')");
// obviously you need to do some error checking, but here's the happy flow
$status = "OK";
$error = "";
$data['names'] = $name;
$data['surnames'] = $surname;
echo json_encode(array(
"status" => $status,
"error" => $error,
"remark" => $extraInfo,
"data" => $data
));
?>
Please be aware this is an example that I have created here in the editor and not in a real working setup. SO please try to understand it instead of copy-pasting it and giving it a run.
I wrote the content of the dialog (div) in another file and used
$("#div").load("content.php", {x:parameter_1, y:parameter_2, ......});
instead of
$.ajax({ type: "POST", url: "show_lecturer.php", data: { x: names, y: surname} })
This did the trick.
Now the div is initially invisible and empty, but once the button is clicked, it requests the content.php page to load. Since I'm passing the search parameters when I request the content, I get the data that I wanted.
The problem from before was that when the page loaded, the div was created with the data (even though I hadn't clicked any button). Therefore, when I 'd click a button, it would show me the div with the content from the last page load (last refresh).
There were also other minor changes I had to do to make it work, but this is the main idea.