How to add javascript in php code function.php error - javascript

This is a script that I want to initialize to my website: https://css-tricks.com/lazy-loading-responsive-adsense-ads/ I upload these script to my server and give address in the footer:
<script type="text/javascript" src="/wp-content/themes/js/jquery.adsenseloader.js"></script>
<script type="text/javascript" src="/wp-content/themes/js/adsenseloader.js"></script>
The next step is to initialize it on the WordPress website and the problem is when I trying to add it in function.php it shows me an error:
The error is
Your PHP code changes were rolled back due to an error on line 218 of file wp-content/themes/functions.php. Please fix and try saving again.
syntax error, unexpected 'var' (T_VAR), expecting end of file
I am interested in how to add this code in PHP?
// vanilla
var instance = new adsenseLoader( '.adsense' ); // accepted argument types: Selector String, Element, NodeList, Array
// jQuery
$( '.adsense' ).adsenseLoader();

you can use this code to add code in function.php
add_action('wp_head','addsense_script');
function addsense_script(){
$script = "<script>";
$script .= "var instance = new adsenseLoader( '.adsense' );";
$script .= "$( '.adsense' ).adsenseLoader(); ";
$script .= "</script>";
echo $script;
}

Related

adding php stops my javascript init() working

I have a file written in html and javascript. I have an init function that I used to initialise some variables in javascript. To make this happen I have the following tag in the body statement:
<body onload="init()">
and then later I have the function itself. All seems to work well.
function init() {
// initialisation stuff here
var arr = ["happy", "winter", "hot", "cold", "male", "female", "summer", "spring", "autumn"];
document.getElementById('word').innerHTML = arr[Math.floor(Math.random() * arr.length)];
flag = 0;
}
However, I now want to load some data from a file so that I can replace the arr variable in my init() function with a much longer list of words. So just below the body statement I put the following:
<?php
$words = file('data.txt');
?>
I changed the file extension from html to php so that the php script would run before the page loads. When I change the extension to php it works fine. But as soon as I add those php lines I get an error. When I look using Develops Tools it says - Uncaught Reference Error: Init not defined.
But my init function is still there. Why would adding those php lines affect the javascript init function?
EDIT
I had the following two lines in my init function
// var words = <?php echo '["' . implode('", "', $words) . '"]' ?>;
// alert(words);
I thought they were commented out. But obviously not. If I remove them the code works fine.
However, although it is evident from the run-time inspection that
var words = <?php echo '["' . implode('", "', $words) . '"]' ?>;
alert(words);
is bringing the data into the init function, somehow it is still producing an error.

Javascript does not call file

I am trying to use the solution called in here:
How to keep session alive without reloading page?
Unfortunately I can't get it to work, I have very limited experience with Javascript and jQuery.
This is my index.php
<?php
session_start();
echo session_id();
$_SESSION['id'] = session_id(); //just so there is a variable within the session
?>
EDIT: added jquery library after comment/answer
<script src="http://code.jquery.com/jquery-latest.min.js" type="text/javascript"></script>
<script>
setInterval(function(){
$.post('refresh_session.php')‌​;
}, 60000);
</script>
And this is the refresh_session.php where I write to a file, so I can test if the file is actually being called.
<?php
session_start();
if (isset($_SESSION['id'])){
$_SESSION['id'] = $_SESSION['id']; // or if you have any algo.
}
$date = new DateTime();
$fp = fopen('data.txt', 'a');
fwrite($fp, $date->format('Y-m-d H:i:s') . " " . session_id() ."\n");
fclose($fp);
?>
If I call refresh_session.php manually, I see the date showing up in data.txt.
If I open up index.php and wait for the data.txt file to change, nothing happens.
What am I missing here?
I don't know why, but after copy-paste your javascript code – I've got strange characters in Code Snipped. It can be charset problem. Code looks good, but bracket only looks like bracket. It's not bracket. What it is? I don't know, but look at that what I've got in Code Snipped after pasting your code:
Code will execute if you write it using good charset. Take that working code:
setInterval(function(){
$.post('refresh_session.php');
alert("dsa");
}, 5000);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
By the way – alert is of course only test, you can delete this.
So, the answer is – check your charset.

How to create an Image object with a base-64 source?

I have a remote web page, on which I use CURL and DOMDocument to retrive the src attribute of an image.
I use the following code, mixing JS in a PHP echo
<?php
$toEcho = "";
$toEcho .= // some stuff here...
$toEcho.="
<script>
//I create the object
var img = new Image();
//I set the source with the PHP variable : I get an error because of unexpected token ":"
img.src = $imgsrc;
</script>"
echo $toEcho;
?>
I checked the source, it is valid, and displays properly in my browser(s).
Where could this come from ?
Set the source like this:
img.src = '$imgsrc';

Javascript variables from PHP to JS file ERROR

JS & PHP file as follows
console.log(my_val_json);
<script async src="<?php echo get_template_directory_uri(); ?>/js/java.js"></script>
<?php $my_php_val = array( 'banana', 'orange'); ?>
<script type="text/javascript">
var my_val_json = '<?php echo json_encode($my_php_val); ?>' ;
</script>
Upon refreshing the page multiple times, i get the below error in my console log:
Uncaught ReferenceError: my_val_json is not defined
And sometimes this error also appears on the 1st load.
Please advice as i am unable to find any answers online for 2 days now. Thanks!
** NOTE: when i change async to defer, there are no errors (so far) **

Assigning latitude and longitude in MVCarray

Im trying to fetch my mysql data I've read some article in
https://developers.google.com/maps/documentation/javascript/examples/layer-heatmap
<?php
$locations = mysql_query("select * from locations");
?>
<?php
$lats = ""; // string with latitude values
$lngs = "";
while ($locat = mysql_fetch_array($locations))
{
$lats = $locat['latitude'];
$lngs = $locat['longitude'];
$taxiData = [new google.maps.LatLng($lats,$lngs)];
}
?>
instead of var taxiData = [new google.maps.LatLng(37.782551, -122.445368)];
now Im trying to fetch the value in those latitude and longitude.
You're trying to execute the js example in PHP. Really, U'll need to learn a bit about web development, but You can try something like this trying to make it working right now:
<?php /* You should add all needed external js scripts above */?>
<script type="text/javascript">
//Here You should put everything before the points array declaring from the example
<?php
$locations = mysql_query("select * from locations");
echo 'var taxiData = [';
while ($locat = mysql_fetch_array($locations))
echo "new google.maps.LatLng({$locat['latitude']}, {$locat['longitude']}),\n";
echo '];';
//Here You should put everything after the points array declaring from the example
?>
</script>
The code above is terrible, but the js part will be sent to the browser and the browser will try to execute it. Anyway, U should take a read a little about web development, otherwise a lot of simple things will be hard enough for You. Good luck.
You seem to be mixing php and javascript with abandon. If you want to issue a javascript command, you have to make sure it looks like javascript to the browser. Maybe something like
<?php
$locations = mysql_query("select * from locations");
?>
<?php
$lats = ""; // string with latitude values
$lngs = "";
while ($locat = mysql_fetch_array($locations))
{
$lats = $locat['latitude'];
$lngs = $locat['longitude'];
$taxiString = "new google.maps.LatLng($lats,$lngs)";
?>
<script type="text/javascript">
var taxiData = [<?=$taxiString?>];
// do whatever you want in javascript
</script>
}
?>
A tested snippet that demonstrates the idea (I could not test the above easily):
<html>
<?php
for($i=0;$i<2;$i++) {
$myString = "It works $i times!";
echo $myString;
?>
<script type="text/javascript">
alert("<?= $myString; ?>");
</script>
<?php
}
?>
</html>
When you run that you will see that the php string $myString was properly inserted into the JavaScript.
Let me clarify a little bit more.
Javascript is code that is executed by the BROWSER. php is code that is executed on the SERVER. The BROWSER will be asking Google Maps for some information - it is your task to make sure that the command that the browser issues is correct. php is nice in that it allows you to change the text that appears in the browser.
The way to understand the difference is to look at the source code of a web page in your browser. The second snippet I posted above is actually available on http://www.floris.us/SO/mix.php
When you open it in your browser, and you look at the source code, you will see
<html>
It works 0 times!<script type="text/javascript">
alert("It works 0 times!");
</script>
It works 1 times!<script type="text/javascript">
alert("It works 1 times!");
</script>
</html>
Breaking it down a little bit ( and adding some carriage returns for clarity):
<html> - this was text in my original file
It works 0 times! - this was the result of a php echo command
<script type="text/javascript"> - literal text in original file
alert(" - literal text
It works 0 times! - the result of <?= $myString; ?>
"); - literal text
</script> - literal text
And then something crazy - the same thing repeats (because of the php loop) - BUT WITH A DIFFERENT VALUE (1 instead of 0):
It works 1 times!<script type="text/javascript">
alert("It works 1 times!");
</script>
</html> - this last line did not repeat because it's outside the php loop
Final comment:
<?= $myString; ?>
is shorthand for
<?php echo $myString; ?>

Categories

Resources