adding php stops my javascript init() working - javascript

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.

Related

How to add javascript in php code function.php error

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;
}

JavaScript Reflection to Find Where a Function Is Defined

I'm working on a large JavaScript project where a lot of external scripts are included. How can I find where a function is defined without having to resort to searching every file on the server?
PHP, for example, has a class named "ReflectionFunction" which is able to return information about a function:
$function_name = 'array_orderby';
$function_info = new ReflectionFunction( $function_name );
echo "The $function_name function is located in: " . $function_info->getFileName() . ' on line: ' . $function_info->getStartLine() . '.';
Sample Output
The array_orderby function is located in: /var/www/mysite.com/inc/script.php on line: 49.
Is there something like that in JavaScript?

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.

setInterval - load PHP with POST - return image

I'm trying to use setInterval() to reload an image from a given path. I have some similar code to reload a log file which is working fine:
var auto_refresh = setInterval(
function auto_refresh_log()
{
$('#log_output').load('refresh_log.php').fadeIn("slow");
}, 1000);
refresh_log.php:
<?php $file = "/var/www/html/mainLOG";
$contents = file($file);
$string = implode( $contents);
echo $string; ?>
Now, I want to do something similar only with 2 changes:
Instead of using a fixed path like in refresh_log.php, I want to pass the path from the JS function to the PHP file. How can I do that?
Instead of returning a string, I want to return an image, which is then used in my html document. How can I do that?
To be exact on what I want to do: I have an index.php on which a user can select a file path. After setting some further parameters, some calculations start in the background. The results are saved as TIFF-files which cannot be read by the browser. So I want to use a PHP script with imagemagick to convert them (which is working fine) and pass them back to the JS. Then, the image should be displayed on my HTML <img id="image_id" ... > and refreshed every couple of seconds just like the log file.
Thanks!
One way would be to change the src attribute of the img element.
The browser will download the resource when you change the the src of the img element. Use the jQuery attr to do this. You should append a timestamp parameter so the browser does not obtain a cached instance from the local browser cache.
function loadImg(src) {
// append a parameter of "_" to the url
$("#myimg").attr("src", src + "?_=" + Date.now());
}
setInterval(loadImg("path/to/img"), 1000);
On your PHP side you would need a script that servers the image up in your converted format from where ever you are storing it. An example of how to do that is here.
I've managed to come up with a solution using $.post instead of $.load. The function is called via:
setInterval(
function auto_refresh_img()
{
var img_path = document.getElementById("image_path").value;
$.post('refresh_img.php',
{path: img_path},
function(data) {
$('#my_div').html(data);}
);
}, 1000);
with refresh_img.php looking like this:
<?php $imagepath = $_REQUEST['path'];
if (file_exists($imagepath)) {
$img = new imagick($imagepath."[0]");
$img->setImageFormat('jpg');
$thumbnails0 = $img->getImageBlob();
echo "<img src='data:image/jpg;base64,".base64_encode($thumbnails0)."' id='reco_background' style='display:none' />";
}
else {
echo "Image does not exist.";
};
?>
The returned <img ... > may then be used for any purpose.

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