I have a requirement where on clicking button, I need to show all the links captured. The java script code would be in a separate file test.php, and the links are captured in an additional file links_generation.php. The function 'getLinks()' has a conditional flow that if no of links is less than 5, it would display all the links, else it would display 5 links and additional text that "x more links are there".
Now, I have a requirement where on click of button, I would like to show all the links captured. I'm not sure how to capture this using javascript.
can someone pleaser help how to proceed with this.
function getLink($result,$currency,$lang) {
foreach($result as $id => $data) {
$num++;
if($num <= 5) $list = $list.linkName(substr($id,3));
}
$list = substr($list, 0, -2);
echo "<li>".$lang['pagelike1']." ".$lang['pagelike2'].": ";
echo $list;
if($num > 5) echo "...".$lang['and']." ".($num-5).$lang['other_ad'];
echo "</li>";
}}
PS: the code is slightly modified,and pls be assured that this is working. I would need to incorporate the new functionality. Would appreciate your help.
Related
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.
<?php
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
}
?>
A way to deactivate/disable W3 Total Cache on specific pages is to use another plugin called: "Plugin Organizer" by Jeff Sterup.
After installing and enabling it, go to settings (of the plugin) and follow the instructions to set it in the right way.
Once the plugin is enabled and settings are saved correctly, when you edit/create a new page using the editor you can see a checkbox that's show you which plugin to enable for that particular page and which to disable.
In this way you can disable W3 Total Cache on the page that's use your function on functions.php.
Hope it helps.
The most common way to bypass the cache is to serve this data via the WordPress json api and use java script to put the always fresh data into place.
The problem is not that the variable inside the code is being cached; what happens is that W3 Total Cache grabs the first page produced by your PHP code and store it in the hard disk of the server. Thenceforth, the browsers' requests are answered delivering the HTML static file stored in server's hard disk (PHP will not produce the same page again).
To solve this problem, you must transfer the "intelligence" inside your PHP code, which is responsible for create slightly different versions of your page, to your Javascript code. Bastian Haustein suggested one way to do that, using WordPress REST API. However, I would try first doing it in a simpler way: after page load, capture the link of your cached page and modify it according to the location of your visitor. Naturally, you will have to capture visitors geolocation also using JS - see the link suggested by cjmling: How to get visitor's location (i.e. country) using geolocation?
I want my code when someone clicks the link then a link will open random of 3 posts between */android.html ,*/samsung.html and */xiaomi.html.
My code is like this
<?php
$YuuClass->update_dls($file['downloads'], $file_id);
echo '<script type="text/javascript">
var x=Math.floor((Math.random()*3)+ 1);
var xxx=null;
if(x=="1"){xxx="android.html"}
if(x=="2"){xxx="samsung.html"}
if(x=="3"){xxx="xiaomi.html"}
</script>';
redirect('https://safelink-ainodorama.blogspot.com/2017/02/"+xxx+"?url='.base64_encode($copy['webContentLink']));
exit();
?>
Where "+xxx+" will change random between */android.html ,*/samsung.html and */xiaomi.html when I click it.
I tried to click it with code like that only showing base64code.
Ex-link when I click
http://myweb.web.id/0aHR0cHM6Ly9kcml2ZS5nb29nbGUuY29tL2Evc2RuMTgzcGVrYW5iYXJ1LnNjaC5pZC91Yz9pZD0xMUNoa0JpS3lvWkRMMGIxTWxYek4yeUt2NGRQcnJoMG8mZXhwb3J0PWRvd25sb2Fk
I want when I click it the URL will be like this
https://safelink-ainodorama.blogspot.com/2017/02/android.html?url=base64_code_here
where android.html can change randomly from 2 another page android, Samsung and Xiaomi.
Because javascript is client-side and php is server-side the javascript wont change xxx.
Instead have an array of your pages, then use array_rand to pick a random one.
Something like:
<?php
$YuuClass->update_dls($file['downloads'], $file_id);
$page = [
'android.html',
'samsung.html',
'xiaomi.html'
];
$url = 'https://safelink-ainodorama.blogspot.com/2017/02/'.$page[array_rand($page)].'?url='.base64_encode($copy['webContentLink']);
redirect($url);
exit;
it's been 3 days trying to fully understand why i can't make this script function for keyboard navigation.
Search, display and replace are working fine, but when i try to browse the List and press Enter to select one option, it does not.
The Form
<form action="/busqueda.php" method="get" autocomplete="off">
<input name="dataa" class="boxbuscar" type="text" id="despliega" onKeyUp="autocomplet()">
<input src="/img/btn-buscar.png" type="image" class="lupa">
<ul id="lista"></ul>
The PHP
<?php
function connect()
{
return new PDO('mysql:host=localhost;dbname=dbname', 'dbuser', 'dbuserpw', array(
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
));
}
$pdo = connect();
$keyword = '%' . $_POST['keyword'] . '%';
$sql = "SELECT * FROM tbl_productos WHERE nombre LIKE (:keyword) ORDER BY nombre ASC LIMIT 0, 15";
$query = $pdo->prepare($sql);
$query->bindParam(':keyword', $keyword, DO ::PARAM_STR);
$query->execute();
$list = $query->fetchAll();
foreach($list as $rs)
{
// put in bold the written text
$reemplazador = str_replace($_POST['keyword'], '<b>' . $_POST['keyword'] . '</b>', $rs['nombre']);
// add new option
echo '<li onclick="set_item(\'' . str_replace("'", "\'", $rs['nombre']) . '\')">' . $reemplazador . '</li>';
}
?>
and the JS
function autocomplet() {
var min_length = 2; // min caracters to display the autocomplete
var keyword = $('#despliega').val();
if (keyword.length >= min_length) {
$.ajax({
url: 'ajax_refresh.php',
type: 'POST',
data: {
keyword: keyword
},
success: function(data) {
$('#lista').show();
$('#lista').html(data);
}
});
} else {
$('#lista').hide();
}
}
// set_item : this function will be executed when we select an item function set_item(item) {
// change input value
$('#despliega').val(item);
// hide proposition list
$('#lista').hide();
}
Any ideas?
Update:
Short answer: This is a better option a link
Keyboard navigation of the list doesn't work out of the box like you want it to. You need to listen to the keyboard events on the list and trigger corresponding actions. Try something along the lines of:
$(document).on('keyup', function(e) {
if (e.which === 38) {
// Arrow Up is pressed
}
if (e.which === 40) {
// Arrow Down is pressed
}
if (e.which === 13) {
// Enter is pressed
}
})
Then you want to have a variable, let's call it current which stores the currently highlighted list item. You will change current when arrow up/down is pressed. You'll also have to add some style to the current list item to indicate which one is highlighted to the user. When enter is pressed, you just call set_item(current) - passing current list item to set_item function.
You also should probably add/remove this listener when the list is shown/hidden, so it doesn't fire on the document when the list is hidden.
Here are the docs for JQuery keyup event. Also check out a tutorial on JavaScript keyboard events.
That all said, you might be better off not reinventing the wheel and using a ready autocomplete widget. Here is JQuery UI Autocomplete, here is Awesomplete (search for "Ajax example" on the page to see an example implementation with the backend server).
P.S. Here is some advice about your code:
don't render javascript on the server. The best way to receive the list from the server would be to receive a JSON object listing all the items and then build list out of it. If you have to return HTML, don't put javascript callbacks in it. So just return <li data-item='1'>One</li> and then use $('#list li').on('click', ... to set the listener for all the items. This way you keep javascript and php as separate as possible
use English for naming variables, functions, etc. One day you will have show your code to someone and using variable names in spanish will make it very difficult for non-Spanish speakers to read your code
learn to use indentation. Proper indentation makes it far more easier to read your code and understand what is going on. Here is a javascript style guide. You can probably find the same thing for PHP as well. There are also online tools that can do it for you try this one. I recommend properly styling your code before posting it in a question, so it will be easier for the community to read.
enter does not work automatically you have to tie your function to enter key event
Within a self-hosted WordPress blog post, I'm trying to share a Youtube video, and then have links also within that post that tell the player to jump to specific times. WordPress strips JavaScript from links, which would be the easy way to control the player. Such as:
1:00
YouTube JavaScript reference
https://developers.google.com/youtube/js_api_reference
Is there a simple plugin that enables this? Is there some specific way for me to format JavaScript so that it will not be stripped from a blog post?
Further example use...
[myvideo]
Link to 1:11
Link to 2:22
Link to 5:55
Not sure if this is too simplistic a method, but since Youtube allows links like: http://youtu.be/g_FEVa75H8g?t=2m36s
would it not be easier just to link the times manually?
e.g. Link to 1:11 would be http://youtu.be/g_FEVa75H8g?t=1m11s
You're missing the other API reference: Shortcode API, just like the [myvideo] you're already using.
It would be like [videolinks times="60,150,230" showtimes="1m,2m30s,3m50s"].
And the shortcode code:
add_shortcode( 'videolinks', 'my_shortcode_handler' );
function my_shortcode_handler( $atts, $content = null )
{
$output = '';
$count = 0;
$times = explode( ',', $atts['times'] );
$showtimes = explode( ',', $atts['showtimes'] );
foreach( $times as $time )
{
$output .= sprintf(
'Link to %s<br />',
$time,
$showtime[$count]
);
$count++;
}
return $output;
}
On my index.php page I use the jquery load() to load other pages in a div "bodycontent". This works fine and dandy. I disable regular links, and must make the href the page name, without the php, and tag the php back on when the load() occurs. One of my pages I'm loading in the div I have dialog boxes pop up on links.
When you initially go to the page, this works fine, but if you steer away by clicking on "products" or any other link on the page at all, and then go back to "home" and click on a link "read more", the dialog boxes will not show up again. You have to refresh, and then it will work until you click a link again. Also, this works fine in my IE 9, ver9.0.8, but older IE at work (like 8), and at least one other persons chrome the dialog box will not come up at all. There are also IE9's at my work that this will just not work on, despite me deleting temp internet files, ect. On my computer it works fine on brand new downloads of firefox, chrome and IE, so I'm also wondering if my method is backwards compatible and cross browser, and if not what I can do to make it so. I'm also using get script in a function with the load to pull the jquery, jquery ui, and my javascript file for the dialog.
I've also looked at things like ajaxcomplete and such, but being mine initially works, I'm not really sure what to do.
My site main index page loading home.php initially (the news, ect)
Fiddle with my navigation javascript, which makes the pages inactive/active and load()/getscript in the div
dialog.js:
$(document).ready(function() {
$('#dialogbox').dialog({
autoOpen: false,
title: 'Loading title...',
modal: true,
width: 500,
height: 400
});
});
function readMore(id,title,cat,desc,post,auth) {
//alert(id +","+ title +","+ cat +","+ desc +","+ post +","+ auth);
var $dialog = $('#dialogbox').html('Category: '+ cat +'<br/>'+ desc +'<br/>---------------------------------<br/>Posted by: '+ auth +'<br/>' + post);
$dialog.dialog('open');
$dialog.dialog("option","title",title);
}
How I pull to function readMore:
<?php
require('config/dbconfig.php');
$query = "SELECT * FROM news ORDER BY id DESC LIMIT 4";
if ($stmt = $mysqli->prepare($query)) {
/* execute statement */
$stmt->execute();
/* bind result variables */
$stmt->bind_result($idn, $titlen, $categoryn, $descn, $postdaten, $authorn);
/* fetch values */
while ($stmt->fetch()) {
//echo 'id: '. $id .' title: '. $title;
echo "<table border='0'>";
$shortDescLengthn = strlen($descn);
if ($shortDescLengthn > 106) {
$sDCutn = 106 - $shortDescLengthn;
$shortDescn = substr($descn, 0, $sDCutn);
} else {
$shortDescn = $descn;
}
echo "<h1>$titlen</h1>";
echo "<tr><td>$shortDescn...</td></tr>";
echo '<tr><td><a href="javascript:void(0);" onclick="'
. 'readMore(' . $idn . ',' . htmlspecialchars(json_encode($titlen)) . ','
. htmlspecialchars(json_encode($categoryn)) . ','
. htmlspecialchars(json_encode($descn)) . ',' . htmlspecialchars(json_encode($postdaten)) . ','
. htmlspecialchars(json_encode($authorn)) . ')">Read More</a></td></tr>';
echo "<tr><td>Written by: $authorn</td></tr>";
echo '<tr><td><img src="images/hardcore-games-newsbar-border.png" width="468px" /></td></tr>';
}
echo "</table><br />";
/* close statement */
$stmt->close();
}
/* close connection */
$mysqli->close();
?>
So again, basically I need to see why this isn't working after I click a link, and how it can be more cross browser and backwards browser compatible.
All I had to do was add:
$('#bodycontent').empty();
before the load(), and it works on every computer I've tried so far. I'm guessing the div needed to be emptied before loading new html in it, so going back it was keeping the js and such from getscript and messing up. Also only kept the single js file that was required only by home.php to be loaded, and put everything else in the index page (like it should have been anyways).