How to prevent those PHP variables from being cached on WordPress? - javascript

I'm using this code in functions.php on WordPress to generate an affiliate link based on the visitor location, It's working perfectly but the problem is that if page caching is turned on (W3 Total Cache), The variables get cached so if someone from the UK was the first one to open the page then the second one from Germany opened the page he will get the same link that the first visitor got.
One more thing please, I'm still very new to PHP and javascript so I would appreciate if the answer was simplified enough
add_action( 'woocommerce_before_add_to_cart_button', 'affiliate_link', 10);
function affiliate_link() {
$not_avilable_country = '<div id="amz_not_avilable" class="amz_not_avilable">This product is not avilable in your country yet</div>';
// IP Geolocation
$country_code = $_SERVER ["HTTP_CF_IPCOUNTRY"];
// Get Custom Fields
$de_asin = get_post_meta(get_post()->ID, "wccaf_de_asin", true );
$uk_asin = get_post_meta(get_post()->ID, "wccaf_uk_asin", true );
//////////////////////////////////////////////
if ($country_code=="DE" or $country_code=="DE") {
$amazon_domain = 'https://www.amazon.de';
// $associate_id = 'bonstato-21';
$asin = $de_asin;
}
else if ($country_code=="GB" && $uk_asin!=="") {
$amazon_domain = 'https://www.amazon.co.uk';
// $associate_id = 'bonmedico-21';
$asin = $uk_asin;
}
///////////////////////////////////////////////
if( wp_is_mobile() ) {
// Amazon Link For Mobile
?>
<script>
function amzGo(){
window.location='<?php echo $amazon_domain ?>/dp/<?php echo $asin ?>/?tag=<?php echo $associate_id ?>';
}
</script>
<?php
} else {
// Amazon Link For PC
?>
<script>
function amzGo(){
window.location='<?php echo $amazon_domain ?>/gp/aws/cart/add.html?AssociateTag=<?php echo $associate_id ?>&ASIN.1=<?php echo $asin ?>&Quantity.1=1';
}
</script>
<?php
}
?>
<div class="buy_amz_btn_wrap" >
<button type="button" id="buy_amz_btn" class="buy_amz_btn" onclick="amzGo();"><i class="fa fa-amazon fa-amz"></i><?php echo $amz_btn_title ?></button>
</div>
<?php
}

Not sure if it will work, but you could try to set some initial values for the variables and a timestamp and after to use an if statement to check if current timestamp is greater than initial one and inside the {} to set the variables.

Related

Create a redirect based on applied coupon in WooCommerce order received page

Here is the flow:
Customer adds product to cart.
Customer adds coupon "smile" at checkout.
When customer places order the function will run before the Order
Details page loads. Function will check for "smile" coupon and if it
has been applied it redirects to a new page where they will be
offered additional products for free. If not, then it continues on
as normal.
I have been referencing two solutions I found through a Google search similar to parts of my problem. Individually I get them to work but together I cannot seem to get them to work correctly.
Here is my code:
add_action( 'woocommerce_thankyou' , 'sq_checkout_custom_redirect' );
function sq_checkout_custom_redirect($order_id) {
global $woocommerce;
$order = new WC_Order( $order_id );
$coupon_id = 'smile';
$applied_coupon = $woocommerce->cart->applied_coupons;
$url = 'https://site.mysite.org/score-you-win/';
if( $applied_coupon[0] === $coupon_id ) {
echo "<script type=\"text/javascript\">window.location.replace('".$url."');</script>";
} else {
echo '<h3 style="font-size:200px; z-index:30000; color:#000 !important;">Coupon not applied</h3>';
}
}
No matter what coupon I apply I get the message "Coupon not applied." and no redirect happens.
The two solutions that I am referencing are:
Find applied coupon_id in cart
Redirect with JS
This code runs successfully:
add_action( 'woocommerce_thankyou', function ($order_id){
$order = new WC_Order( $order_id );
$coupon_id = "smile";
$url = 'https://site.mysite.org/score-you-win/';
if ($order->status != 'failed') {
echo "<script type=\"text/javascript\">window.location.replace('".$url."');</script>";
}
});
And this runs successfully:
function product_checkout_custom_content() {
global $woocommerce;
$coupon_id = 'smile';
$applied_coupon = $woocommerce->cart->applied_coupons;
if( $applied_coupon[0] === $coupon_id ) {
echo '<span style="font-size:200px; z-index:30000; color:#red !important;">We are happy you bought this product =)</span> ';
} else {
echo '<h3 style="font-size:200px; z-index:30000; color:#000 !important;">Coupon not applied</h3>';
}
}
add_action( 'woocommerce_thankyou' , 'sq_checkout_custom_redirect' );
Updated: In woocommerce "Order Received" page (thankyou), there is no more WC_Cart object available. Instead you need to target the WC_Order object this way:
add_action( 'woocommerce_thankyou', 'thankyou_custom_redirect', 20, 1 );
function thankyou_custom_redirect( $order_id ) {
// Your settings below:
$coupon_id = 'smile';
$url = 'https://site.mysite.org/score-you-win/';
// Get an instance of the WC_order object
$order = wc_get_order($order_id);
$found = false;
// Loop through the order coupon items
foreach( $order->get_items('coupon') as $coupon_item ){
if( $coupon_item->get_code() == strtolower($coupon_id) ){
$found = true; // Coupon is found
break; // We stop the loop
}
}
if( $found )
echo "<script type=\"text/javascript\">window.location.replace('".$url."');</script>";
else
echo '<h3 style="font-size:200px; z-index:30000; color:#000 !important;">Coupon not applied</h3>';
}
Code goes in function.php file of your active child theme (or active theme). Tested and works.

how to send record to table after click the js link/button?

i want to make an like-unlike button below the post. registered user can give like. i have make the button, but i don't have idea how to send a record when user click the button. i guess i need like table, so this below is table and it field that i have :
user : id_user, username
posting : id_post, id_user, content
like : id_like, id_user, id_post
posting page and like button script :
<?php
include "database_connection.php";
$query=$dbc->query("select user.username, posting.content FROM posting inner join user on user.id_user = posting.id_user where id_post='$_GET[id]'");
$array= $query->fetch_array()
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="post.js"></script>
</head>
<body>
<?php echo $array['username'];?>
<?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
<a class="like-button" href="#"><i class="fa fa-thumbs-up"></i></a>
<!--LIKE BUTTON END-->
</body>
</html>
post.js
$(function() {
$('.like-button').click(function(){
var obj = $(this);
if( obj.data('liked') ){
obj.data('liked', false);
obj.html('<i class="fa fa-thumbs-up"></i>');
}
else{
obj.data('liked', true);
obj.html('<i class="fa fa-thumbs-down"></i>');
}
});
});
Alright, so I've taken the time to create a basic working example for you.
I've included the workings of post.js in an inline script rather than a separate file for simplicity with including a PHP variable inside of the script.
Your HTML Page
<?php
include "database-connection.php";
$user = 1;// get your accessing user ID (not user id of poster)
$post = $_GET['id'];
// query checks whether user has liked the post or not and returns it as well
$query=$dbc->prepare("
SELECT `user`.`username`, `posting`.`content`, IFNULL(`like`.`id_like`,0) AS `id_like`
FROM `posting`
INNER JOIN `user` ON `user`.`id_user` = `posting`.`id_user`
LEFT JOIN `like` ON `like`.`id_user` = ? AND `like`.`id_post` = ?
WHERE `posting`.`id_post`=?");
// bind the parameters to avoid injection
$query->execute(array($user, $post, $post));
$array= $query->fetch(PDO::FETCH_ASSOC);
?>
<!doctype html>
<html>
<head>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<script type="text/javascript">
// previously post.js
$(function() {
$('.like-button').click(function(e){
e.preventDefault();
var obj = $(this);
// ajax query that returns a JSON object with the result of the request
$.getJSON('likes.php',{post:obj.data('post'), user: <?php echo $user; ?>}, function(data){
//console.log(data); // uncomment for debugging
if(data.error){
// query returned error, handle it however you want
} else {
if (data.like == 1){ // user now likes the post
obj.html('<i class="fa fa-thumbs-up"></i>');
} else { // user now doesn't like the post
obj.html('<i class="fa fa-thumbs-down"></i>');
}
}
});
});
});
</script>
</head>
<body>
<?php echo $array['username'];?>
<?php echo $array['content'];?>
<!--THIS IS LIKE BUTTON-->
<?php
if ($array['id_like']==0){
// user hasn't liked the post, show thumbs down
echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-down"></i></a>';
} else {
// user has liked the post, show thumbs up
echo '<a class="like-button" href="#" data-post="'.$post.'"><i class="fa fa-thumbs-up"></i></a>';
}
?>
<!--LIKE BUTTON END-->
</body>
</html>
likes.php (the PHP script)
<?php
include "database-connection.php";
$post = $_GET['post'];
$user = $_GET['user'];
$result = (object) ['like'=>null, 'post'=>$post, 'user'=>$user];
$q = $dbc->prepare("SELECT id_like FROM `like` WHERE id_post=? AND id_user=?");
$q->execute(array($post, $user));
$r = $q->fetch(PDO::FETCH_OBJ);
if ($q->rowCount() > 0){
$like = $r->id_like;
} else {
$like = 0;
}
if ($like == 1){
// user likes post, so we unlike it by setting id_like to 0 (for false)
$like = 0;
$u = $dbc->prepare("UPDATE `like` SET id_like = 0 WHERE id_post=? AND id_user=?");
} elseif ($q->rowCount()>0) {
// update because the record exists
$like = 1;
$u = $dbc->prepare("UPDATE `like` SET id_like = 1 WHERE id_post=? AND id_user=?");
} else {
// create the record because it doesn't exist yet
$like = 1;
$u = $dbc->prepare("INSERT INTO `like` (id_like, id_post, id_user) VALUES(1, ?, ?)");
}
if($u->execute(array($post, $user))){
// update succeeded
$result->like = $like;
} else{
// there was an error
$result->error = 'failed to execute in database';
}
// return the json object to your page
echo json_encode($result);
Again, this is just the basics of how this would work. You will have to research logins, sessions, and security for yourself to manage the user who are accessing, posting, and liking the content. But I hope this helps!
Send the request to PHP page on click of like button and handle it there to update the database.
You will need to send an Ajax request to the server and then handle in in a PHP script.
Here's a way to do that.
post.js:
$(function() {
$('.like-button').click(function(){
var obj = $(this);
if( obj.data('liked') ){
obj.data('liked', false);
obj.html('<i class="fa fa-thumbs-up"></i>');
}
else{
obj.data('liked', true);
obj.html('<i class="fa fa-thumbs-down"></i>');
}
$.post('url/to/your_script.php', {
action: 'updateLikeStatus',
status: obj.data('liked'),
post_id: obj.data('id') // ID of the object that user "liked"
});
});
});
You can read more about jQuery.post() here. And here's documentation on more general jQuery.ajax() method.
your_script.php (script that deals with Ajax requests) might look something like this:
<?php
include "database_connection.php";
if (isset($_POST['action']) && $_POST['action'] === 'updateLikeStatus') {
$id_user = $_SESSION['user_id'];
$id_post = $_POST['post_id'];
if ($_POST['status'] === true) {
// adding "like"
$query = $dbc->query("
INSERT INTO like
(id_user, id_post)
VALUES ({$id_user}, {$id_post});
");
$query->query();
} else {
// removing "like"
$query = $dbc->query("
DELETE FROM like
WHERE id_user = {$id_user}
AND id_post = {$id_post};
");
$query->query();
}
}
Note that this code is just an example, you shouldn't use it directly in the production. For one thing, you can't put variables from $_POST directly into a MySQL query, because it will create an SQL Injection type vulnerability, allowing people to perform arbitrary queries on your server. One way to avoid it is by using prepared statements.
Another problem is that you will need to deal with the user authentication and authorization. I've used $_SESSION['user_id'] in my example, but it won't work unless you initialize session and populate user_id value first. Sessions are required so that one user can't like posts on behalf of another user. You can read more about sessions here.

Creating a PHP Session using jQuery / JS

On page load, I want to check if a PHP Session variable exists:
If it does, alert() the contents
If it doesn't, create it and save the current time
Here is my code:
$(document).ready(function(){
<?php if(session_id() == '') { session_start(); } ?>
if (!<?php echo isset($_SESSION['lbBegin'])?'true':'false'; ?>) {
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
This code works in the sense that the first page load doesn't produce an alert() and a refresh shows the time, however every refresh / link click afterwards changes the time. I was expecting the time to stay the same during the entire session.
What have I done wrong?
You need to add session_start() at the very beginning and check if a session variable exists. Do this way:
<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){
if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
// And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
</script>
Correcting the AJAX Bit:
<?php session_start(); // At the very top! No matter what! ?>
<script>
$(document).ready(function(){
if (!<?php echo isset($_SESSION['lbBegin']) ? 'true' : 'false' ; ?>) {
// And you cannot do the below thing, because, first PHP executes before JS even runs. So, you need to use an AJAX Call for this:
$.getScript("setTime.php");
} else {
alert("<?php echo $_SESSION['lbBegin']; ?>")
}
});
</script>
Inside the setTime.php add the code:
<?php $_SESSION['lbBegin'] = date("Y-m-d H:i:s"); ?>

append PHP code to HTML input placeholder?

I want to append a PHP function that shows the user his/her IP within an inputs' placeholder. I've never seen anything like this been done before so I'd like to just see if it's possible or not.
My thoughts right now is to do something along these lines:
$('input').attr(placeholder,function(){
$('input').append('<?php $variable ?>');
});
then run the PHP code through here some how. If someone can shed some light on this I would be very grateful!
try this:
$('#inputID').attr("placeholder","<?php echo $variable; ?>");
And if you want to append to all inputs:
$(":input").attr("placeholder","<?php echo $variable; ?>");
should do the work
If you want to do it in PHP you can make a function to retrieve the IP of the user then echo the script in your page:
<?PHP
function getUserIP()
{
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
echo "<script type='text/javascript'>
$('input').attr(placeholder,function(){
$('input').append('".getUserIP()."');
});
</script>";
?>

Auto load search results when page loads

I am using a joomla module i would like to modify to auto load the default list of results.
currently, when the page loads no result is shown. If all search fields are empty and the user clicks the search button, the page will load all data. If information in placed in the search fields, the results will be broken down to match what was typed in.
I want the page to auto load all data when the page loads without the user clicking search.
How do i achieve this?
I believe the module uses ajax and i believe the info that affects this is below:
<?php
header('Access-Control-Allow-Origin: *');
header('Content-Type: text/html');
define('_JEXEC', 1);
define('DS', DIRECTORY_SEPARATOR);
ini_set("display_errors", "On");
error_reporting(E_ALL & ~E_STRICT & ~E_NOTICE & ~E_WARNING);
$my_path = dirname(__FILE__);
$my_path = explode(DS.'modules',$my_path);
$my_path = $my_path[0];
if (file_exists($my_path . '/defines.php')) {
include_once $my_path . '/defines.php';
}
if (!defined('_JDEFINES')) {
define('JPATH_BASE', $my_path);
require_once JPATH_BASE.'/includes/defines.php';
}
require_once JPATH_BASE.'/includes/framework.php';
$app = JFactory::getApplication('site');
$app->initialise();
///////////////////////////////////////////////////////////////////////////////////////////////
$name = $_GET['name'];
$value = mb_strtolower($_GET['value']);
$next = mb_strtolower($_GET['next']);
$db = JFactory::getDBO();
$query = "SELECT * FROM #__k2_extra_fields WHERE published = 1";
$db->setQuery($query);
$results = $db->loadObjectList();
$extra_val = '';
$extra_id = 0;
foreach($results as $result) {
if(trim(mb_strtolower($result->name)) == trim($value) . " " . trim($next) || trim(mb_strtolower($result->name)) == trim($next) . " " . trim($value)) {
$extra_val = $result->value;
$extra_id = $result->id;
break;
}
}
require_once(JPATH_ADMINISTRATOR.DS.'components'.DS.'com_k2'.DS.'lib'.DS.'JSON.php');
$json = new Services_JSON;
$extra_val = $json->decode($extra_val);
if($extra_val != '') {
foreach($extra_val as $val) {
echo "<option>" . $val->name . "</option>";
}
echo "<option>".$extra_id."</option>";
}
?>
Please help!
to auto load search result we must need to store search query in session variable,
http://docs.joomla.org/How_to_use_user_state_variables
http://docs.joomla.org/API15:JApplication/getUserStateFromRequest
This are the links which will describe very well about how to manage request variable in session, so there is no variable in request it will get value from the session.
try to use something like this
<html>
<head>
<script>
function myFunction()
{
alert("Page is loaded");
}
</script>
</head>
<body onload="myFunction()">
<h1>Hello World!</h1>
</body>
</html>
then you can easily change myFunction to trigger your search on click event
<script>
function myFunction()
{
document.getElementById('YOUR-BUTTON-ID').onclick();
}
</script>

Categories