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) **
Related
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;
}
I'm trying to set a cookie in PHP, and then have my JavaScript/jQuery read it. As I've been trying to research the issue I've seen some people talk about server side vs. client side cookies, and other people saying cookies are just cookies and there's no difference. What I do know is that PHP sees the cookies, and JavaScript doesn't.
Here's a simplified version of the PHP file that builds the page and sets the cookies.
<!DOCTYPE html>
<?php
setcookie("card", "", time()+900, '/');
?>
<html>
<body>
<?php
$card = "a string I want in my cookie";
$_COOKIE['card'] = $card;
foreach($_COOKIE as $c => $c_value)
{
echo "Cookie named " . $c . " has value " . $c_value . "<br/>";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.cookie#1.4.1/jquery.cookie.min.js"></script>
<script type = "text/javascript" src = "script.js"></script>
</body>
</html>
This will correctly show the name and value of the cookie on my page. So I know I'm setting something.
But when my JavaScript runs, I don't seem to have any cookies. I tried a couple different ways to get to the value of either all cookies, or just a single target part of the cookie:
var all_cookies = document.cookie;
var aCard = $.cookie('card');
all_cookies shows up with a value of "" when I debug, and aCard just stays undefined.
So do I need to set the cookies differently with PHP? Or read them differently with either JavaScript or jQuery?
PHP's setcookie() function sets an HTTP response header that instructs the browser to set the cookie. This is only possible if you haven't sent any output yet. Calling setcookie() after you have already output the <!DOCTYPE means you should be getting a "Cannot modify header information - headers already sent" warning.
To set a cookie and make it available to Javascript, you need to set it at the very beginning of your script before generating any output:
<?php
$card = "a string I want in my cookie";
setcookie("card", $card, time()+900, '/');
// note from the manual (https://php.net/setcookie):
// Once the cookies have been set, they can be accessed
// on the next page load with the $_COOKIE array.
// ^^^^^^^^^^^^^^^^^^^^^
//
// so the "card" cookie won't be in $_COOKIE until
// the next page load. If you want it in there
// immediately, you need to set it manually:
$_COOKIE['card'] = $card;
?>
<!DOCTYPE html>
<html>
<body>
<?php
foreach($_COOKIE as $c => $c_value)
{
echo "Cookie named " . $c . " has value " . $c_value . "<br/>";
}
?>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/jquery.cookie#1.4.1/jquery.cookie.min.js"></script>
<script type = "text/javascript" src = "script.js"></script>
</body>
</html>
Now that you've used setcookie() before generating any output, the cookie is set properly and Javascript should be able to access it from document.cookie without any trouble.
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.
I have this file:
<html>
</html>
<script>
setInterval(function () {
<?php clearstatcache(); ?>
var ss = "<?php echo filesize('log.html'); ?>";
console.log(ss);
},100);
</script>
But if I empty out the file log.html the browser still outputs the old filesize. Am I doing something wrong here? If so how can I fix it?
Javascript you are running keeps outputting the same data that has been sent when the page loaded. Thus it never change, as it is not reading from server.
You would need to use ajax to re-read data from server whenever needed to update.
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; ?>