Should be simple (but it isn't): Javascript snippet inside PHP - javascript

I have coded in PHP and JS for a while, but I don't do it often, and so I've been snagged by something that should be simple, but it's giving me fits. And none of the answers I've found here have solved the problem.
I have JS slideshow code that is inserted into a WordPress page when multiple images named [pagename]1,2,3...png are present in the images folder. I've struggled to get the code to read the folder, and now it does. But the JS slideshow is not working on the "Menu" page, while the exact same code is working on the "Home" page. The only difference between the two is that the Menu code tests whether images are present in the images folder. (They are.)
This first part of the code is, I feel certain, correct. The second piece of code is where the issue is. Why is the JS not starting my slideshow? It should. The code reads properly on the page.
<?php
$uploads = wp_upload_dir();
$x = 1;
$poname = $post->post_name;
if ($dir = opendir('/home/rowlandwilliams/public_html/lepeep/wp-content/themes/twentythirteen-child/images')) {
$images = array();
while (false !== ($file = readdir($dir))) {
if ($file != "." && $file != "..") {
$images[] = $file;
asort($images);
}
}
closedir($dir);
}
And this is where I think the problem is:
foreach($images as $image) {
$subimg = substr($image, 0, -5);
if ($subimg == $poname) {
if ($x == 1) {
echo "<script type='text/javascript'>
function cycleImages(container) {
var $active = container.find('.active');
var $next = ($active.next().length > 0) ? $active.next() : container.find('img:first');
$next.css('z-index',2);
$active.fadeOut(1500,function() {
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
$(document).ready(function() {
setInterval(function(){cycleImages($('#page-cycler'))}, 2000);
})
}
</script>"; ?>
<div class="cycler" id="page-cycler">
<?php $actstat = 'class="active"'; ?>
<?php $x++; ?>
<?php } else { ?>
<?php $actstat = ''; ?>
<?php } ?>
<img <?php echo $actstat; ?> src="<?php bloginfo('stylesheet_directory'); ?>/images/<?php echo $image; ?>">
<?php } ?>
<?php } ?>
</div><!-- #page-cycler -->
http://rowlandwilliams.com/lepeep/menu/

This is where your problem is:
echo "<script type='text/javascript'>
function cycleImages(container) {
var $active = container.find('.active');
var $next = ($active.next().length > 0) ? $active.next() : container.find('img:first');
$next.css('z-index',2);
$active.fadeOut(1500,function() {
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
$(document).ready(function() {
setInterval(function(){cycleImages($('#page-cycler'))}, 2000);
})
}
</script>";
When you use " to echo with, php will parse all $var...
So the variable $activeand $next is being echoed from php, which doesn't look like it's set anywhere in your code. The solution would either be to change variable names from $active to active or to use single quotes ' instead of double quotes "

Using single quotes (') will tell PHP not to parse any variables inside the echo, while using double quotes (") will.
Try using ' quotes, and replace any ' quotes inside the JS with " quotes.
echo '<script type="text/javascript">
function cycleImages(container) {
var $active = container.find(".active");
var $next = ($active.next().length > 0) ? $active.next() : container.find("img:first");
$next.css("z-index",2);
$active.fadeOut(1500,function() {
$active.css("z-index",1).show().removeClass("active");
$next.css("z-index",3).addClass("active");
});
$(document).ready(function() {
setInterval(function(){cycleImages($("#page-cycler"))}, 2000);
})
}
</script>';

Your code is mess, I have rewrite your code for more clean, maybe. Since you there is no php code inside your javascript, don't try to use echo it will make your code even mess and as #Arian mentioned, $active and $next will be work as php variable.
foreach($images as $image):
$subimg = substr($image, 0, -5);
if ($subimg == $poname):
if ($x == 1): ?>
<script type='text/javascript'>
function cycleImages(container) {
var $active = container.find('.active');
var $next = ($active.next().length > 0) ? $active.next() : container.find('img:first');
$next.css('z-index',2);
$active.fadeOut(1500,function() {
$active.css('z-index',1).show().removeClass('active');
$next.css('z-index',3).addClass('active');
});
$(document).ready(function() {
setInterval(function(){cycleImages($('#page-cycler'))}, 2000);
})
}
</script>
<div class="cycler" id="page-cycler">
<?php
$actstat = 'class="active"';
$x++;
else:
$actstat = '';
endif; ?>
<img <?= $actstat; ?> src="<?php bloginfo('stylesheet_directory'); ?>/images/<?= $image; ?>">
<?php endif; ?>
<?php endforeach; ?>
</div><!-- #page-cycler -->

Related

Using variable on php to create another variable in JS

I'm having a hard time getting the value of a specific variable in php to use in js. This is my code in php:
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
}
?>
I want to get the value of this ($result['status']) and pass it on the variable pos in js. This is my js code:
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
var pos = $('PHP VARIABLE HERE').val();
alert(pos);
}
Thanks for your help.
The easiest way is to output it to javascript directly:
?>
<script type="text/javascript">
window.MY_PHP_VAR = <?php echo json_encode($myPhpVar); ?>;
</script>
...
window.MY_PHP_VAR now contains your php variable
if your javascript code is on same page where the result is comming then you can use this
var pos = `<?php echo $result['status'] ?>`;
var pos = `<?= $result['status'] ?>`;
===============
// refresh.php
===============
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<h4>" . $result['status'] . "</h4>";
echo "<script> alert('". $result['status'] ."'); </script>";
/* If the $result['status'] is 'success' the above line will be converted to:
echo "<script> alert('success'); </script>";
*/
}
?>
so, every time the refresh.php loads, the script is going to get executed.
However, I suggest you to assign a id or class attribute to your h4 where you are echoing your status and access the value using the selectors in the javascript.
you could try giving an id or class to the status.
then in JavaScript you could then get the value of the id or class.
PHP
<?php
require("connection.php");
$sql_cmd = "SELECT * FROM tbstatus";
$stmt = $con->prepare($sql_cmd);
$stmt->execute();
echo "<h2>STATUS OF THE BABY</h2>";
while ($result = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo '<h4> <span class="status">' . $result['status'] . '</span></h4>';
}
?>
JavaScript
var oldStatus = '';
setInterval(function() {
$("#position").load('refresh.php');
notif();
}, 1000);
function notif() {
// note that since we used a class, you will get the value of the first element only.
var pos = $('.status').text(); // use .text() instead of .val()
if (pos.toLowerCase() == 'out' && pos != oldStatus){
oldStatus = pos;
alert(pos);
}
}

can I put javascript inside the brackets of a script tag with src on it? [duplicate]

This question already has answers here:
Using HTML script tags to code while they have a source
(2 answers)
Closed 6 years ago.
I use these variables assigned by PHP in my linked javascript file below. Just wondering if its ok to do this:
<script src="js/settings.js">
var chores = <?php if ($chores == 0) echo "false"; else echo "true"; ?>;
var contacts = <?php if ($contacts == 0) echo "false"; else echo "true"; ?>;
var gyms = <?php if ($gyms == 0) echo "false"; else echo "true"; ?>;
var meetings = <?php if ($meetings == 0) echo "false"; else echo "true"; ?>;
var spirituals = <?php if ($spirituals == 0) echo "false"; else echo "true"; ?>;
</script>
Or should I do this:
<script>
var chores = <?php if ($chores == 0) echo "false"; else echo "true"; ?>;
var contacts = <?php if ($contacts == 0) echo "false"; else echo "true"; ?>;
var gyms = <?php if ($gyms == 0) echo "false"; else echo "true"; ?>;
var meetings = <?php if ($meetings == 0) echo "false"; else echo "true"; ?>;
var spirituals = <?php if ($spirituals == 0) echo "false"; else echo "true"; ?>;
</script>
<script src="js/settings.js"></script>
Both seem to work fine. I don't know why I'm nervous about the top one.
If the js file (js/settings.js) uses the variables assigned in the document then you should include the javascript file after the variables have been assigned otherwise you're likely to get 'undefined' error.
If js/settings.js use something like $(document).ready(... in which the variables are used after the document is loaded then either way would be fine.
Ideally, in my opinion you should always include the script files after

PHP variable with a value of string is not equal in PHP variable with a value of html id from javascript?

This is my example code
<script>
var item = "yooow";
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
echo $str_html; //it will output "yooow"
?>
but...
when i'm trying to compare this into another php variable
<?php $str_php ="yooow";
if($str_html == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>
but it returns to false
how can they be an equal?
PHP is run serverside which means it's not aware of any changes you make in the DOM using Javascript.
<script>
var item = "yooow";
Value set only in clinet side, PHP don't know about changes here
jQuery("#view").html(item);
</script>
<?php $str_html = '<p id="view"></p>';
WRONG, it will output "<p id="view"></p>"
echo $str_html; //it will output "yooow" ?>
<?php $str_php ="yooow";
Comparing "<p id="view"></p>" and "yoow" and that is not equal!
if($str_html == $str_php)
Better, you give the item value in cookie/session. And, compare the cookie value with $str_php.
<?php session_start(); ?>
<script>
$(document).ready(function(){
var item = "<?php echo $_SESSION['html']="yooow"; ?>";
$("#view").html(item);
});
</script>
<?php
$str_html = '<p id="view"></p>';
$strHtml=$_SESSION['html'];
$str_php ="yooow";
if($strHtml == $str_php)
{
echo "true";
}
else
{
echo "false";
}
?>

How to know if a PHP variable is being retrieved by JavaScript?

I'm having some trouble in JS function for combobox. It functions well if there is a PHP variable being passed, but if there's nothing, the whole block of code doesn't work. I've tried using if(typeof(<?php echo json_encode($information['day']) ?>)!='undefined') but it still doesn't work. Is there another way on how to determine if the PHP variable is set or passed?
There are more ways to do this than I can think of. Here is one.
<script>
<?php if( isset($information) && isset($information['day']) ) { ?>
var myJson = <?php echo json_encode($information); ?>;
<?php } else { ?>
var myJson = null;
<?php } ?>
if(myJson != null) {
// do something
}
</script>
Change this line of code
if(typeof(<?php echo json_encode($information['day']) ?>)!='undefined')
to this
if(typeof("<?php echo json_encode($information['day']); ?>") != 'undefined')

HTML Escaping/Encoding in Javascript/PHP

I have multiple pages of html code saved into a database. I want a file to be able to flip through each of these pages without reloading.
I created a PHP file to pull all the pages into a database.
The page shows the first page and navigation buttons.
There is also javascript to put all the other pages into an array so I can quickly switch pages.
var pages = new Array();
<?php foreach ($coursePages as $page): ?>
pages[pageCount] = "<?php echo ($page['body']) ?>";
pageCount++;
<?php endforeach ?>
My problem is creating the javascript array. How can I escape the data from the echo properly so it can eventually change the page content using the following:
$(document).ready(function() {
$('.navNext, .navPrevious').click(function({
if ($(this).hasClass('navNext')) {
page++;
if (page > pageCount) {
page = 0;
}
} else {
page--;
if (page < 0) {
page = 0;
}
}
$('.page').html(pages[page]);
}))
});
Anytime you send values dynamically from PHP to JavaScript, you can simply use json_encode(). It will always produce valid JavaScript and handle all data types. Example:
<script>
var a = <?php echo json_encode($var)?>;
</script>
you can use this function to escape js values:
function js_escape_string($str)
{
$str = str_replace("\\", "\\\\", strval($str));
$str = str_replace("'", "\\'", $str);
$str = str_replace("\r", "\\r", $str);
$str = str_replace("\n", "\\n", $str);
$str = str_replace("\t", "\\t", $str);
$str = str_replace("</script>", "</'+'script>", $str);
return $str;
}
NOTE: use single quote ' around JS values, like:
<script>
var a = '<?php echo js_escape_string(....); ?>';
</script>

Categories