I'm having trouble passing a PHP array to Javascript [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 7 years ago.
Improve this question
I'm using PHP and javascript to create a banner function. All of my images are in the folder Images/banners, and are being dynamically added by PHP, and then added to theJavaScript array "adImages". That part is working fine, as I can see the array in the JavaScript when I viewsouce. However, the images are not being placed on the page.
Here is my code, what am I missing?
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Banners</title>
<?php
$dir = 'Images/banner';
$files = scandir($dir);
array_shift($files);
array_shift($files);
?>
<script language="Javascript" type="text/javascript">
// Setting variables
dir = Images/banner/
adImages = <?php echo json_encode($files); ?>;
thisAd = 0
imgCt = adImages.length
// Rotate function
function rotate() {
if (document.images) {
thisAd++
if (thisAd == imgCt) {
thisAd = 0
}
document.adBanner.src=dir+adImages[thisAd]
setTimeout("rotate()", 1 * 1000)
}
}
</script>
</head>
<body onload="rotate()">
<center>
<img src="" name="adBanner" alt="Ad Banner" />
</center>
</body>
</html>

Seems to work for me after making your dir var a string. Using your Chrome Developer Tools / Console pointed the errors out for you. The following code works for me with two sample images:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Rotating Banners</title>
<?php
$dir = 'Images/banner';
$files = scandir($dir);
array_shift($files);
array_shift($files);
?>
<script language="Javascript" type="text/javascript">
// Setting variables
var dir = "Images/banner/",
adImages = <?php echo json_encode($files); ?>,
thisAd = 0,
imgCt = adImages.length;
// Rotate function
function rotate() {
if (document.images) {
thisAd++
if (thisAd == imgCt) {
thisAd = 0
}
document.adBanner.src=dir+adImages[thisAd]
setTimeout("rotate()", 1 * 1000)
}
}
</script>
</head>
<body onload="rotate()">
<center>
<img src="" name="adBanner" alt="Ad Banner" />
</center>
</body>
</html>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="jquery.js"></script>
<?php
$dir = '';
$files = array();
$dir = 'Images/banner';
$aExclusion = array( '..', '.' );
$files = array_diff(scandir($dir), $aExclusion);
$files = array_values( $files );
echo '<script>';
echo "var adImages = [];";
echo 'var oData = ' . json_encode( $files ) . ';';
echo '</script>';
?>
<script>
$(document).ready(function()
{
// Get banner count minus one for array offset.
iBannersSize = Object.keys(oData).length - 1;
// Ensure we have at least 1 banner to rotate.
if( iBannersSize > 0 )
{
window.setInterval(function(){
iChangeToImage = Math.round( Math.random() * ( iBannersSize - 0 ) );
$("div#banner_wrapper img").attr("src", 'Images/banner/' + oData[ iChangeToImage ] );
console.log( oData[ iChangeToImage ] );
}, 2000 );
}
});
</script>
</head>
<body>
<center>
<div id="banner_wrapper">
<!-- Render first banner on page load -->
<img src="<?php echo 'Images/banner/' . $files[ 0 ]; ?>" alt="Ad Banner">
</div>
</center>
</body>
</html>

Related

Javascript call php function and receives back results

This postprovides sample code using obtaining a server file list as an example. Here is the code I have used:
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>How to create form using jQuery UI</title>
<link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.3/themes/pepper-grinder/jquery-ui.css" media="screen" rel="stylesheet" type="text/css">
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.0/jquery.min.js"></script>
<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.10.2/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(function() {
$.get('getfilename.php', { dir : '/ajax1/' }, function(data) {
// you should now have a json encoded PHP array
$.each(data, function(key, val) {
alert('index ' + key + ' points to file ' + val);
});
}, 'json');
alert ("ok");
});
</script>
</head>
<body>
<h1>Get file names... </h1>
</body>
</html>
getfilename.php
$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
$filesArray = array();
$Counter = 0;
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[$Counter] = $file;
echo $filesArray[$Counter].'';
$Counter++;
}
}
echo json_encode($filesArray);
My problem is that the javascript alert alert('index ' + key + ' points to file ' + val); fails to display anything on the page. The script is working because I get a response in the Firebug console log.
ajax.jsajax.phpindex.html["ajax.js","ajax.php","index.html"]
What I need to change on the script to return this information to the html page so that I can use the JSON for further processing ?
Thanks.
With your debug you broke the JSON output in PHP. So, remove:
echo $filesArray[$Counter].'';
Also, before any output, you should add JSON header:
header('Content-Type: application/json');
At the end, your PHP file should look like this:
$dir = $_REQUEST['dir'] ;
$dir = $_SERVER['DOCUMENT_ROOT'] . $dir;
$filesArray = array();
$files = scandir($dir);
foreach ($files as &$file) {
if ($file!='.' && $file!='..' ) {
$filesArray[] = $file;
}
}
header('Content-Type: application/json');
echo json_encode($filesArray);

Pass and print a $_GET variable through php load file by javascript

I searched for a solution of passing a get variable obtained from index.php page to included.php file[ loaded by javascript ]. A nice solution by php require function is given Pass and print a $_GET variable through an included file by php require function
However, in my case I have
for index.php => url[ index.php?var=item]
<?php
if(isset($_GET['var'])) {
$var=$_GET['var'];
}
?>
<script>
$(document).ready(function(){
$("#ok").load("included.php");
});
</script>
<div id='ok'>
</div>
in included.php [which will be loaded in index.php by javascript load function]
<?php
echo $var;
?>
The error was the undefined var in included.php file.How Can I echo this variable with a combination of php and javascript ?
If you want to pass these variables on to the included file you could go with
$("#ok").load("included.php?<?php echo $urlString; ?>");
The URL string can be generated with this function
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
Another option would be :
$( "#ok" ).load( "included.php", { "choices[]": [ "Jon", "Susan" ] } );
Based upon the first example:
index.php:
<?php
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
if(isset($_GET['var']) === true) {
$var=$_GET['var'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Test</title>
<script type="text/javascript">
$(document).ready(function(){
$("#ok").load("included.php?<?php echo GenGetVars(); ?>");
});
</script>
</head>
<body>
<div id='ok'>
</div>
</body>
</html>
included.php
<?php
echo print_r($_GET, true);
?>
index.php:
<?php
function GenGetVars(){
$Base = NULL;
foreach($_GET as $key => $variable){
$Base .= '&'.$key.'='.$variable;
}
return(rtrim($Base, '&'));
}
if(isset($_GET['var']) === true) {
$var=$_GET['var'];
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />
<title>Test</title>
<script type="text/javascript">
function LoadScriptFile(){
/// SENDING THE INFORMATION BY AJAX
$.ajax({
type : "POST", /// SEND TYPE
url : "getScriptName.php", /// TARGET FILE TO RETRIEVE INFORMATION
data : {
'SomeParamID' : 1,
'AnotherParamID' : 'Dunno.. just something'
},
///######## IN CASE OF SUCCESS
success:function(response){
if( response != "" ){
$.getScript( 'js/' + response + '.js', function( data, textStatus, jqxhr ) {
console.log( data ); // Data returned
console.log( textStatus ); // Success
console.log( jqxhr.status ); // 200
console.log( "Load was performed." );
});
}
else{
alert( "Error retreiving data" );
}
}
}
);
}
</script>
<script type="text/javascript">
$(document).ready(function(){
$("#ok").load("included.php?<?php echo GenGetVars(); ?>");
});
</script>
</head>
<body>
<div id='ok'>
</div>
</body>
</html>
included.php
<?php
echo print_r($_GET, true);
?>
getScriptName.php
<?php
switch($_POST['SomeParamID']){
case 1:
echo 'MyGreatJSFile';
break;
case 2:
echo 'MyNotSoGreatJSFile';
break;
}
?>
You could try this.

how to auto refresh multiple php variables without refreshing page? I can only do one atm

I'm trying to auto-refresh multiple PHP variables. So far I can only auto-refresh one variable and the rest do not work (it will always be the last one that works, so var2).
I was thinking of making a JSON script and trying to do it like that but how would I go about making each array in the JSON to auto-refresh on my PHP page without refreshing the whole page?
index.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script language="javascript" src="jquery-1.2.6.min.js"></script>
<script language="javascript" src="jquery.timer-1.0.0.js"></script>
<link rel="stylesheet" href="css/bootstrap.css">
<link rel="stylesheet" href="css/bootstrap.min.css">
<script src="jquery-1.9.0.min.js"></script>
<?php $ra = "<div id='c1b'></div>
<script type='text/javascript'>
$(document).ready(function() {
$('#c1b').load('var1.php');
refresh();
});
function refresh(){
setTimeout( function() {
$('#c1b').fadeOut('slow').load('var1.php').fadeIn('slow');
refresh();
}, 2000);
}
</script>";
$rb = "<div id='c2b'></div>
<script type='text/javascript'>
$(document).ready(function() {
$('#c2b').load('var2.php');
refresh();
});
function refresh(){
setTimeout( function() {
$('#c2b').fadeOut('slow').load('var2.php').fadeIn('slow');
refresh();
}, 2000);
}
</script>"; ?>
<?php echo $ra . ' & ' . $rb ?>
var1.php
<?php
include_once 'connect.php';
$d= 'var1';
$q = $handler->prepare("SELECT * FROM var WHERE name = ?");
$q->bindParam(1, $d);
$q->execute();
while($r = $q->fetch()){
$e = $r['names'];
}
echo $e;
?>
var2.php
<?php
include_once 'connect.php';
$d= 'var2';
$q = $handler->prepare("SELECT * FROM var WHERE name = ?");
$q->bindParam(1, $d);
$q->execute();
while($r = $q->fetch()){
$e = $r['names'];
}
echo $e;
?>
As best as I can read this, you're going to have two functions named "refresh" defined on your page.
Try changing the script in your second one to a unique name, e.g.
$(document).ready(function() {
$('#c2b').load('var2.php');
refreshvar2();
});
function refreshvar2(){
setTimeout( function() {
$('#c2b').fadeOut('slow').load('var2.php').fadeIn('slow');
refreshvar2();
}, 2000);
}

PHP variable in JavaScript doesn't print

I've been reading all the questions about how to print a PHP variable in JavaScript but all the answers I read until now don't work for me and I'm going crazy.
This is my code:
<?php
$MyPHPStringVar = '321321';
$MyPHPNumVar = 32;
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>o maior</title>
</head>
<body>
<script type="text/javascript">
var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
alert(MyJSStringVar);
alert(MyJSNumVar);
</script>
</body>
</html>
When I run this the alert() shows "" for my phpstring variable and doesn't show nothing for my php number variable.
Why is this?? I'm going nuts because it seems to work for everybody but not me!!
Thanks for your time
use this instead :
<script type="text/javascript">
<?php echo " var MyJSStringVar = "\".$MyPHPStringVar.""\";
var MyJSNumVar = <?php echo $MyPHPNumVar; ?>;
alert(MyJSStringVar);
alert(MyJSNumVar);
</script>
#ToBe, here is the code:
<?php
$MyPHPStringVar = '321321';
$MyPHPNumVar = 32;
?><!DOCTYPE HTML>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>o maior</title>
</head>
<body>
<script type="text/javascript">
var MyJSStringVar = "<?php print($MyPHPStringVar); ?>";
var MyJSNumVar = <?php print($MyPHPNumVar); ?>;
alert(MyJSStringVar);
alert(MyJSNumVar);
</script>
</body>
</html>
It's the same!
Use echo instead of Print. Something like -
var MyJSNumVar = <?php echo $MyPHPNumVar; ?>;
Also if your php.ini has short tags turned on you can use -
var MyJSNumVar = <?=$MyPHPNumVar?>;
It was an error on the PHP engine.
I reinstalled it with Microsoft Web Plataform Installer along with the new ISS8.0 and it's working great!

getting errors in php coding something undefined variable

I am getting following error in this code : Strict Standards: Only variables should be passed by reference in C:\xampp\htdocs\uploader\upload.php on line 12
Success
also other error are Notice: Undefined variable: fulltarget in C:\xampp\htdocs\uploader\upload.php on line 101
Notice: Undefined variable: fulltarget in C:\xampp\htdocs\uploader\upload.php on line 101
Here is the pastebin link to see the whole code : http://pastebin.com/JKegmNHC
Also here is the code also available.. you can see it through here or using the pastebin link to get the error indication right from the related line....
Here is the code :
<?php
$submit=$_POST['sub'];
if(isset($submit))
{
$name=$_FILES['img']['name'];
$type=$_FILES['img']['type'];
$size=($_FILES['img']['size'])/1024;
$ext=end(explode('.',$name));
if (($ext == "gif")
|| ($ext == "jpeg")
|| ($ext == "jpg")
|| ($ext =="png")
&& ($size > 30))
{
############################## File Renaming ###################################################
$newname=uniqid();
//$ext=end(explode('.',$name));
$fullname=$newname.".".$ext;
$target="pics/";
$fulltarget=$target.$fullname;
if(move_uploaded_file($_FILES['img']['tmp_name'],$fulltarget))
{
echo "Success";
}
else
{
echo "Failed";
}
############################## File Renaming end ###################################################
}
else{
echo "not successful";
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="abhi.css" />
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Php Image Uploader</title>
</head>
<body>
<div id="a1">
<form name="frm" method="post" enctype="multipart/form-data">
<input type="file" name="img" /><br />
<input type="submit" name="sub" value="Store" />
</form>
</div>
<div id="a2">
<?php echo "
<html>
<head>
<title>Aviary Photo Editer</title>
<!-- Load Feather code -->
<script type='text/javascript' src='http://feather.aviary.com/js/feather.js'></script>
<!-- Instantiate Feather -->
<script type='text/javascript'>
var featherEditor = new Aviary.Feather({
apiKey: 'ceegvx4siylhayrr',
apiVersion: 3,
theme: 'dark', // Check out our new 'light' and 'dark' themes!
tools: 'enhance,frames,crop,orientation,brightness,saturation,sharpness,draw,redeye,blemish,effects,stickers,resize,focus,contrast,warmth,colorsplash,text,whiten',
appendTo: '',
onSave: function(imageID, newURL) {
var img = document.getElementById(imageID);
img.src = newURL;
},
onError: function(errorObj) {
alert(errorObj.message);
}
});
function launchEditor(id, src) {
featherEditor.launch({
image: id,
url: src
});
return false;
}
</script>
</head>
<body>
<div id='injection_site'></div>
<img id='image1' src='$fulltarget'/>
<p><input type='image' src='http://images.aviary.com/images/edit-photo.png' value='Edit photo' onclick=\"return launchEditor('image1', '$fulltarget');\" /></p>";
?>
</body>
</html>
As per the [PHP: end - Manual], when you use end() it passes the last element in the array as a reference.
You can try a couple things:
Don't use explode() in end(). Try doing the explode when you declare $name:
$name = explode( '.', $_FILES['img']['name'] );
Use array_slice() and list() instead of end():
list($ext) = array_slice( explode( '.' , $name ), -1 );
Either one would probably work.
You get 'Notice: Undefined variable' errors because you try to use a variable without initializing it first. In your HTML you use '$fulltarget', but it's only set after you submitted the form. If you want to get rid of this notice you should put something like $fulltarget = ''; after your PHP opening tag.
If you will check the PHP end() function documentation http://php.net/manual/en/function.end.php you will see that the function takes an array as a parameter through reference. To fix this error you should save your explode() results as a variable and then pass that variable to end() function. For example: $arr = explode('.', $name); $ext = end($arr);

Categories