Insert JS Snippet To WP Site - javascript

I've been slowly truing to teach myself some simple aspects regarding coding. Right now, I want to upload a snippet of JS code onto a single page. Here is some background followed with the code I want to use:
The code will go on one page. This page is a form page where if someone does anything other than press "submit" a module pops up with some questions. I've been using wordpress. Any thoughts, guidance, etc. would be perfecto!
<script>
var config = new Object();
config.surveyID = 3160325;
/*config.animationMode = 0;*/
config.takeSurveyURL = 'http://www.surveyanalytics.com/a/TakeSurvey';
config.windowPositionLeft = 200;
config.windowPositionTop = 300;
config.home = 'http://www.surveyanalytics.com/';
config.isRightToLeft = false;
config.surveyStartMessage = 'Start Survey';
config.popupInvitationLaterMessage = 'Later';
config.showFooter = true;
config.invitationDelay = 0;
config.skipCount = 0;
config.popupMode = 0;
config.expirationTime = 60
window.onbeforeunload = function() {
QP_popupMain();
};
</script>
<script language="javascript" type="text/javascript" src="http://www.surveyanalytics.com//javascript/exitSurveyInvitation.js"></script>
<noscript>
Start Survey Survey
</noscript>

Since WordPress doesn't like <script> tags within functions.php, instead put your code into a ".js" file and register the script in functions.php and then enqueue it in your shortcode.
In your functions.php file:
add_action( 'wp_enqueue_scripts', 'register_my_script' );
function register_my_script() {
//This example puts it in plugins, but you can put it in your theme instead
wp_register_script( 'script-name', plugins_url( '/js/script.js' , __FILE__ ), array(), '1.0.0', true );
}
//Replace "PUT YOUR JAVASCRIPT CODE IN HERE" with your actual code
function myTestFunction( $atts )
{
//Now enqueue the script
wp_enqueue_script( 'script-name' );
}
add_shortcode( 'myjavascriptfunction', 'myTestFunction' );
Then in the CMS, go to that page and add the call to the shortcode in the content text box:
[myjavascriptfunction /]

This is the code in script.js
<script>
var config = new Object();
config.surveyID = 3160325;
/*config.animationMode = 0;*/
config.takeSurveyURL = 'http://www.surveyanalytics.com/a/TakeSurvey';
config.windowPositionLeft = 200;
config.windowPositionTop = 300;
config.home = 'http://www.surveyanalytics.com/';
config.isRightToLeft = false;
config.surveyStartMessage = 'Start Survey';
config.popupInvitationLaterMessage = 'Later';
config.showFooter = true;
config.invitationDelay = 0;
config.skipCount = 0;
config.popupMode = 0;
config.expirationTime = 60
window.onbeforeunload = function() {
QP_popupMain();
};
</script>
<script language="javascript" type="text/javascript" src="http://www.surveyanalytics.com//javascript/exitSurveyInvitation.js"></script>
<noscript>
Start Survey Survey
</noscript>
This is the code in function.php
add_action( 'wp_enqueue_scripts', 'register_my_script' );
function register_my_script() {
//This example puts it in plugins, but you can put it in your theme instead
wp_register_script( 'script', plugins_url( '/script.js/' , __FILE__ ), array(), '1.0.0', true );
}
//Replace "PUT YOUR JAVASCRIPT CODE IN HERE" with your actual code
function myTestFunction( $atts )
{
//Now enqueue the script
wp_enqueue_script( 'script' );
}
add_shortcode( 'myjavascriptfunction', 'myTestFunction' );

Related

How can I start JavaScript with a button click (on WordPress)?

I want to insert a button in a page WordPress that open this a JavaScript when a click happened.
The HTML script is this
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
</head>
<body>
<script type="text/javascript">
test=()=>{
var script = document.createElement('script');
script.src = 'https://www.jdoodle.com/assets/jdoodle-pym.min.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
}
</script>
<input type="button" onclick="test()" value="test">
<div height="200px" width="300px" data-pym- src="https://www.jdoodle.com/iembed/v0/x6e?rw=1"></div>
</body>
</html>
I've tried to insert a jquery version like this.
On wordpress page
<button onclick="F()">Click me</button>
and in functions.php
function javascript_footer() {
?>
<script>
// your javscript code goes
function F(){
alert("test");
$.getScript("https://www.jdoodle.com/assets/jdoodle-pym.min.js", function(data, textStatus, jqxhr) {
});
alert("stop");
}
</script>
<?php
}
add_action('wp_footer', 'wpb_hook_javascript_footer');
What's is wrong? it seems that it doesn't load property the script.
Thank you.
Enqueue your script.
See wp_enqueue_script() for more details.
/**
* Enqueue a script with jQuery as a dependency.
*/
function wpdocs_scripts_method() {
wp_enqueue_script( 'custom-script', get_stylesheet_directory_uri() . '/js/custom_script.js', array( 'jquery' ) );
}
add_action( 'wp_enqueue_scripts', 'wpdocs_scripts_method' );
Your problems though
Is that you're currently not declaring your anonymous function test()
Try:
const test = () => {
var script = document.createElement('script');
script.src = 'https://www.jdoodle.com/assets/jdoodle-pym.min.js';
var head = document.getElementsByTagName("head")[0];
head.appendChild(script);
}

Getting jquery post value and checking it with php

Briefly, i work on to create a Wordpress plugin. In this plugin, i need a progress bar that moving on according to background process. So, I determined a specific php file which contains my custom functions. Let's call this 'func.php' . Also, there is a file that acts as plugins main page file. We can call it 'main.php' .
So; I designed a concept in my head. On the main page, when I click begin button (named 'buttonbegin'), a jquery post being sent to func.php . I can control this POST value with these codes in func.php:
if (isset($_POST['action'])) {
switch ($_POST['action']) {
case 'buttonbegin':
func1();
break;
case 'otherbutton':
func2();
break;
}
}
After it, func1 executes. In this function, i had these codes for testing:
function func1() { ?>
<script type="text/javascript">
jQuery(document).ready(function($) {
var itemnumber=0;
for (var i = 1; i <= 3000; i++) { //it should be execute 3000 times because of nature of process
itemnumber++;
if (itemnumber == 30) {
var value = "mystring";
var ajaxurl = 'fullurl+pluginsdirectory/main.php', //func.php and main.php are in same folder
data = {'action': value};
$.post(ajaxurl, data, function (response) {
});
itemnumber=0;
}
}
});
</script>
<?php
}
At this point in this func1, I wanna do another jquery post to make a trigger mechanism for progress bar on main.php . And finally, there is some javascript code to control this last jquery post and expand 1% progress bar. Here is the script codes in main.php :
<script type="text/javascript"> //below are for the first process i told
var width = 0;
var addition = 1;
jQuery(document).ready(function($) {
$('#buttonbegin').click(function(){
var clickBtnValue = $(this).val();
var ajaxurl = 'fullurl/func.php',
data = {'action': clickBtnValue};
$.post(ajaxurl, data, function (response) {
});
});
//actual part starts here
var continuous = setInterval(function() {
var code = <?php echo !isset($_POST['action']) ?>; // the source of the problem
if(!code) {
var percent = $("#myBar").width() / $("#myBar").parent().width() * 100;
if (percent == 100) {
clearInterval(continuous);
}
var element = document.getElementById("myBar");
element.style.width = (width+addition) + "%";
element.innerHTML = (width+addition) * 1 + "%";
width = width + addition;
}
}, 1000);
});
</script>
But it doesn't work. When i print the 'code' variable with console.log, I see NaN value. The php code inside script tags doesn't work properly. Is there any mistake? Or is there another simpler way to do whole process?
Note: Necessary jquery cdn links are included in main.php and func.php both. This is how its look like:
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<script src="https://code.jquery.com/jquery-3.2.1.min.js" integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4=" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/popper.js#1.12.9/dist/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap#4.0.0/dist/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</head>

Inserting Javascript into admin footer wordpress

I need to add Livechat widget on all WordPress admin pages (backend).
The Livechat JavaScript code is this:
<!-- Start of LiveChat (www.livechatinc.com) code -->
<script type="text/javascript">
window.__lc = window.__lc || {};
window.__lc.license = 12345678;
(function() {
var lc = document.createElement('script'); lc.type = 'text/javascript'; lc.async = true;
lc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.livechatinc.com/tracking.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(lc, s);
})();
</script>
<noscript>
Chat with us,
powered by LiveChat
</noscript>
<!-- End of LiveChat code -->
Livechat has a plugin for the chat to work on the front-end pages. I actually wanted to add this code to every page of WordPress back-end.
I was thinking of putting it in the admin footer through the functions.php of my child theme, but I'm not sure how to put this code together.
The code I am inserting into the child theme is this:
function remove_footer_admin () {
echo 'My footer text. Thank you WordPress for giving me this filter.';
}
add_filter( 'admin_footer_text', 'remove_footer_admin' );
Where should I put this code to work?
You can add JavaScript code in admin footer using admin_footer hook.
If you also need to add same code on the front-end, then apply wp_footer hook too.
Here is a complete code goes in child theme's functions.php:
// Function to render LiveChat JS code
function lh_add_livechat_js_code() {
?>
<!-- Start of LiveChat (www.livechatinc.com) code -->
<script type="text/javascript">
window.__lc = window.__lc || {};
window.__lc.license = YOUR_KEY; // use your license key here
(function() {
var lc = document.createElement('script'); lc.type = 'text/javascript'; lc.async = true;
lc.src = ('https:' == document.location.protocol ? 'https://' : 'http://') + 'cdn.livechatinc.com/tracking.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(lc, s);
})();
</script>
<noscript>
Chat with us,
powered by LiveChat
</noscript>
<!-- End of LiveChat code -->
<?php
}
add_action( 'admin_footer', 'lh_add_livechat_js_code' ); // For back-end
add_action( 'wp_footer', 'lh_add_livechat_js_code' ); // For front-end

Pass order data to AdForm tracking code in Woocommerce thankyou

I am looking to pass along the WooCommerce Variables "OrderID" and "Cart_total" into our Ad Tracking platform.
I was supplied with the tracking code which needed to be implemented and am having issues getting these variables into AdForm.
Here's the snippet, which works perfectly, I think that I am not including the variables correctly.
/**
* #snippet Add Conversion Tracking Code to Thank You Page
* #how-to Watch tutorial # https://businessbloomer.com/?p=19055
* #sourcecode https://businessbloomer.com/?p=19964
* #author Rodolfo Melogli
* #testedwith WooCommerce 3.3.4
*/
add_action( 'woocommerce_thankyou', 'bbloomer_conversion_tracking_thank_you_page' );
function bbloomer_conversion_tracking_thank_you_page() {
?>
<!-- Adform Tracking Code BEGIN -->
<script type="text/javascript">
window._adftrack = Array.isArray(window._adftrack) ? window._adftrack : (window._adftrack ? [window._adftrack] : []);
window._adftrack.push({
pm: XXXXXXXX,
divider: encodeURIComponent('|'),
pagename: encodeURIComponent('conversion'),
order : {
sales: '$woocommerce->cart->get_cart_total();',
orderid: '$order->get_id();'
}
});
(function () { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'https://track.adform.net/serving/scripts/trackpoint/async/'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })();
</script>
<noscript>
<p style="margin:0;padding:0;border:0;">
<img src="https://track.adform.net/Serving/TrackPoint/?pm=XXXXXXX&ADFPageName=conversion&ADFdivider=|" width="1" height="1" alt="" />
</p>
</noscript>
<!-- Adform Tracking Code END -->
<?php
}
Specifically, I was asked to provide the following variables:
sales: '$woocommerce->cart->get_cart_total();',
orderid: '$order->get_id();'
But these are not working. I am unfortunately not a programmer (the programmer is on holiday). I think I need to call the variables somewhere.
There is no more cart data in Order received (thankyou) page, so you surely mean $order->get_total(). Also there is some mistakes in your code.
So you need:
first to get the WC_Order object from the missing $order_id argument in your hoked function
To get order total
To include and display the values in the javascript code.
Try the following:
add_action( 'woocommerce_thankyou', 'bbloomer_conversion_tracking_thank_you_page', 12, 1 );
function bbloomer_conversion_tracking_thank_you_page( $order_id ) {
// Get an instance of the WC_Order object
$order = wc_get_order( $order_id );
?>
<!-- Adform Tracking Code BEGIN -->
<script type="text/javascript">
window._adftrack = Array.isArray(window._adftrack) ? window._adftrack : (window._adftrack ? [window._adftrack] : []);
window._adftrack.push({
pm: XXXXXXXX,
divider: encodeURIComponent('|'),
pagename: encodeURIComponent('conversion'),
order : {
sales: '<?php echo $order->get_total(); ?>',
orderid: '<?php echo $order->get_id(); ?>;'
}
});
(function () { var s = document.createElement('script'); s.type = 'text/javascript'; s.async = true; s.src = 'https://track.adform.net/serving/scripts/trackpoint/async/'; var x = document.getElementsByTagName('script')[0]; x.parentNode.insertBefore(s, x); })();
</script>
<noscript>
<p style="margin:0;padding:0;border:0;">
<img src="https://track.adform.net/Serving/TrackPoint/?pm=XXXXXXX&ADFPageName=conversion&ADFdivider=|" width="1" height="1" alt="" />
</p>
</noscript>
<!-- Adform Tracking Code END -->
<?php
}

How can I load all the website content before call a JavaScript function in php

<?php
$homepage = file_get_contents('https://finance.yahoo.com/quote/0016.HK/news p=0016.HK"');
echo $homepage;
?>
<script type="text/javascript">
function test(){
.....
}
The script was executed before the website load all the contents and thus, I can't get all the content after running the script.
How can I fully get the content from the website first and then run the script? thanks!
<script type="text/javascript">
document.addEventListener( 'DOMContentLoaded', function( event ) {
function test(){
console.log("DOM loaded");
}
});
</script>

Categories