Right integration of complex JavaScript into PHP code - javascript

After hours and hours I can't implement JavaScript code into PHP. JavaScript code is an ad code which I need to implement in WordPress, using functions.php, but every-time I get following error:
identifier "key", expecting ";" in your code
I am trying to create shortcode first and then to use that shortcode anywhere on site, including also injection through PHP, but also directly in content. NOTICE: JavaScript code can not be changed, thus - any customization of JavaScript code is not an option, but I am out of PHP solutions.
My code:
function jsad_code_shortcode() {
return '<script type="text/javascript">
atOptions = {
'key' : '9f8c74bccbdb424a067d31a8a20551a3',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://versatileadvancement.com/9f8c74bccbdb424a067d31a8a20221c6/invoke.js"></scr' + 'ipt>');
</script>';
}
add_shortcode( 'jsad_code', 'ad_code_shortcode' );

Please don't solve it by wrapping your code with HEREDOC syntax. The problem still is that you're writing JavaScript in a PHP context, which should be avoided if possible.
Instead, write your data as a PHP array and encode it to JSON. Both JavaScript and PHP know how to interpret JSON. Use a combination of wp_register_script and wp_add_inline_script to setup your script tags.
add_action('wp_enqueue_scripts', function() {
$at_options_data = json_encode([
'key' => '9f8c74bccbdb424a067d31a8a20551a3',
'format' => 'iframe',
'height' => 90,
'width' => 728,
'params' => (object) []
]);
wp_register_script('jsad', '//versatileadvancement.com/9f8c74bccbdb424a067d31a8a20221c6/invoke.js', [], null, true);
wp_add_inline_script('jsad', "window.atOptions = {$at_options_data};", 'before');
});
After that the only thing that you have to do is to enqueue the script. This will place the script with the rest of the script tags in either the <head> or at the closing </body> tag, depending on your settings. This will also ensure that the script is only printed to the screen once.
add_shortcode('jsad', function() {
wp_enqueue_script('jsad');
});

try this code.
function jsad_code_shortcode() {
ob_start();
?>
<script type="text/javascript">
atOptions = {
'key' : '9f8c74bccbdb424a067d31a8a20551a3',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://versatileadvancement.com/9f8c74bccbdb424a067d31a8a20221c6/invoke.js"></scr' + 'ipt>');
</script>
<?php
return ob_get_clean();
}
add_shortcode( 'jsad_code', 'ad_code_shortcode' );
I think, there are some problems with your js code.

Solution is to use HEREDOC syntax, so the shortcode with this kind of JS should look like as follows:
<?php
function shortcode() {
return <<<EOT
<script type="text/javascript">
atOptions = {
'key' : '9f8c74bccbdb424a067444665654445',
'format' : 'iframe',
'height' : 90,
'width' : 728,
'params' : {}
};
document.write('<scr' + 'ipt type="text/javascript" src="http' + (location.protocol === 'https:' ? 's' : '') + '://versatileadvancement.com/9f8c74bccbdb424a067d31a8a20221c6/invoke.js"></scr' + 'ipt>');
</script>
EOT;
}
add_shortcode( 'shortcode', 'shortcode' );
Thank you all...

Related

How to use AJAX to POST to PHP?

As I asked here I would like to know how I could pass the data from a simple JS function to php, and log it there.
I found this answer and tried to follow it. This is my code right now (both in the same file)
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getClientScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH)
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
<script type="text/javascript">
getScreenResolution();
</script>
</body>
</html>
<?php
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
if(isset($_POST['screenResolutionW'])) {
$fh = fopen('log.txt', 'a');
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH
."\r\n");
fclose($fh);
}
?>
However, this does not work.
I wouldn't know how to fix this, whenever I try to google this problem people use more advanced methods, that I wouldn't even know how to start with.
Edit: My PHP and HMTL are in the same file (index.php).
Edit 2: Removed old code for clarity.
This results in these error messages:
Notice: Undefined index: screenResolutionW in index.php on line 153
Notice: Undefined index: screenResolutionH in index.php on line 154
What you want to do with $.post is include your data like this:
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
where the first of the pair is the POST identifier (the ['screenResolutionW']) and the second of the pair is the variable value.
You will also want to change your POST identifiers to be quoted:
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
Otherwise, you will get a warning about constants. I have also corrected the spelling in these variables, to reflect what you're trying to write into your file.
fwrite($fh, 'Screen res: '."".$screenResolutionW .'x'."".$screenResolutionH ."\r\n");
EDIT
Part of the problem is that you never call the function to execute it. Here is your HTML with the additions I have suggested, plus calling the function:
EDIT TWO
Added an onload handler for the document:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
</head>
<body>
<script>
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("index.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
</script>
</body>
<script type="text/javascript">
$(function() {
getScreenResolution();
});
</script>
</html>
OTHER NOTES
You really should separate the PHP code and place it in a different file because when you run the page as it is now you should get one line logged that has no variables when the page initially runs, then one logged line when the JavaScript fires after the page loads.
Then once separated you should not run your PHP until you test for the existence of a variable, for example:
if(isset($_POST['screenResolutionW'])) {
// your code to write to the file here
}
EDIT THREE
I placed all of the JavaScript in the same script block in the head of the file and have tested again:
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js" type="text/javascript"> </script>
<script type="text/javascript">
$(function() {
function getScreenResolution() {
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
console.log(screenResolutionW + ' ' + screenResolutionH);
$.post("post_test.php", {screenResolutionW: screenResolutionW, screenResolutionH: screenResolutionH})
}
getScreenResolution();
});
</script>
</head>
<body>
</body>
</html>
Here you can see the variables are being posted:
Adapting the others answers.
try it:
function getScreenResolution() {
"http://example.com/index.php", screenResolutionW + screenResolutionH
$.ajax({
url: '/index.php',
method: 'POST',
data: {
screenResolutionW : screen.width,
screenResolutionH : screen.height
},
success: function(data) { console.log(data); }
});
}
And in your PHP
$screenResolutionW = $_POST['screenResolutionW'];
$screenResolutionH = $_POST['screenResolutionH'];
echo $screenResolutionW . " - " . $screenResolutionH;
you have to use serialize the array before doing post request.
var screenResolutionW = screen.width;
var screenResolutionH = screen.height;
var serializedArr = {
width: screenResolutionW,
height: screenResolutionH
};
$.post('/index.php', serializedArr, function(response) {
// Log the response to the console
console.log("Response: "+response);
});
In the server end, you will get values in $_POST variable.
Apart of all those mistakes you have discovered thanks to other replies, you have these:
$screenResoltuionW = ...
Notice you wrote "ltuion" and in the fopen command you have it correct. screenResolutionW
Same thing with $screenResoltuionH...
That's why you don't get any value in the file, because those variables doesn't exists.

jQuery loads the content .phtml into a specific <div> (Magento 2)

It is necessary to load via a script content .phtml > in div.
$(document).ready(function(){
$("button").click(function(){
$("#div1").load("demo_test.txt");
});});
I created testinfo.phtml (external content-file)
and created testcms.phtml, put code:
<?php $TestInfo = $this->getLayout()->createBlock("Magento\Framework\View\Element\Template")->setTemplate("Magento_Cms::testinfo.phtml")->toHtml();?>
<div id="div1"></div>
<button class="testinfo">Get External Content</button>
<script type="text/x-magento-init">
{
"*": {
"Magento_Cms/js/testinfo": {
"testinfo": "<?php echo $TestInfo; ?>"
}
}
}
Created file testinfo.js and put code:
define(["jquery"], function($) {
"use strict";
$(document).ready(function() {
$('.testinfo').click(function() {
$("#div1").load( ? ? ? ? ? ? )
});
});
});
In the load() need to place the URL or data. URL string is not working. What need to insert Data, I cannot understand. I need your advice.

Clipping Magic API

I am currently trying to use the api for clippingmagic but I am running into a problem with defining their callback function. Here is the code I have currently for it.
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js" type="text/javascript"></script>
<script src="https://clippingmagic.com/api/v1/ClippingMagic.js" type="text/javascript">
</script>
<script type="text/javascript">
var errorsArray = ClippingMagic.initialize({apiId: ####});
if (errorsArray.length > 0) alert("Sorry, your browser is missing some required features: \n\n " + errorsArray.join("\n "));
ClippingMagic.edit({
"image" : {
"id" : ######,
"secret" : "#############"
}
}, callback);
</script>
If anyone has worked with their api and can help me, that would be greatly appreciated.
Where are you defining your callback variable? I don't see that callback would actually resolve to a function that you've defined.
ClippingMagic.edit({
"image" : {
"id" : response.image_id,
"secret" : response.image_secret
}
}, function(response) {
if(response.event == 'result-generated') {
# response.image.id
# response.image.image_secret
}
});
I created a clipping magic plugin for WordPress to edit WooCommerce product photos and this is a snippet from it.

how to use Postmedia digital cordova plugin (DFP)

I would like to use DFP (double click for Plublisher) for my android app, I already have the generated scripts and markup as below:
<script type='text/javascript'>
(function() {
var useSSL = 'https:' == document.location.protocol;
var src = (useSSL ? 'https:' : 'http:') +
'//www.googletagservices.com/tag/js/gpt.js';
document.write('<scr' + 'ipt src="' + src + '"></scr' + 'ipt>');
})();
</script>
<script type='text/javascript'>
googletag.defineSlot('/*****/****_APP_1024x66', [1024, 66], 'div-gpt-ad- ********-0').addService(googletag.pubads());
googletag.pubads().enableSyncRendering();
googletag.pubads().enableSingleRequest();
googletag.enableServices();
</script>
DOCUMENT BODY
<div id='div-gpt-ad-**********' style='width:1024px; height:66px;'>
<script type='text/javascript'>
googletag.display('div-gpt-ad-*********');
</script>
</div>)
But, it does not display on Mobile (android project). That's why I would like to use the DFP plugin (PostMedia), but I do not know how to use that? as the plugin itself would not be good enough.
for instance, I have already had the code(above) to put in my app, but I wanna know how can i integrate that plugin with my code.
Note: In the plugin we have:
createBannerAd: function (options, successCallback, failureCallback) {
var defaults = {
'adUnitId': 1404187116182-0,
'adSize': (250, 150),
'tags': undefined,
'networkId': 4271715,
'backgroundColor': "#fff"
};
what if we want to have bunch of ads and of course we have bunch of codes generated by Google and FDP? we need to create a service ? or what?
I really appreciate any response a head,
I am using Cordova 2.8.1 / AngularJS
Here is how we use it
var successCreateBannerView = function() {
//console.log("addBanner Success");
DFPPlugin.requestAd({
'isTesting': false
}, success, error);
};
var success = function() {
//console.log("requestAd Success");
};
var error = function(message) {
//console.log("requestAd Failed " + message);
};
var options = {
'adUnitId': '/xxx/xxxx', // Replace the /xxx/xxxx with your adslot
'adSize': 'BANNER',
'tags': {},
'backgroundColor': '#FFFFFF'
};
DFPPlugin.createBannerAd(options, successCreateBannerView, error);

How can I prevent an external JS file from breaking my site?

I'm currently using Mixpanel on my site. For some reasons they go down from time to time and that disables my site from loading.
Is there a way I can make the load async or some other idea where it doesn't bring down my site when they have downtime?
Here's the code:
<script>
var mp_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
document.write(unescape("%3Cscript src='" + mp_protocol + "api.mixpanel.com/site_media/js/api/mixpanel.js' type='text/javascript'%3E%3C/script%3E"));
</script>
Thanks
Do not document.write it to the page, append it.
<script>
$( function(){
var mp_protocol = (("https:" == document.location.protocol) ? "https://" : "http://");
jQuery.getScript(unescape(mp_protocol + "api.mixpanel.com/site_media/js/api/mixpanel.js"));
});
</script>

Categories