1

Possible Duplicate:
What is the safest way of passing arguments from server-side PHP to client-size JavaScript

Goal: Replace the static file name in the javascript object with php data .

Problem:

I don't know if I my syntax or logic is right as I am not getting any js or php errors. Worst of all my script is not giving the desired results. You can see the actual page at http://www.iamvishal.com/dev/property/burradon-road-burradon line 197

javascript object which I want to make using php:

var data = { 'JPEG/1.jpg': { caption: '' }, 'JPEG/2.jpg': { caption: '' }, 'JPEG/3.jpg': 
{ caption: '' }, 'JPEG/4.jpg': { caption: '' },  'JPEG/5.jpg': { caption: '' },  
'JPEG/6.jpg': { caption: '' },
'JPEG/7.jpg': { caption: '' },  'JPEG/8.jpg': { caption: '' },};

So I need to replace JPEG/1.JPG with a php variable $filename. Below is my code.

<script type="text/javascript">

var data = { ;


<?php
$queryglob ="JPEG/*".$node->field_ropertyid['und'][0]['value'].".jpg";
// Here I am getting all the file names as per my condition.

foreach (glob($queryglob) as $filename) {
// here I am want each file name to be assigned into the javascript object
?>

data = data+'+<?php print $filename ; ?> +':{caption:''}, ;
<?php

}
?>

data = data+};

</script>
Community
  • 1
  • 1
Vishal Khialani
  • 2,557
  • 6
  • 38
  • 49
  • What is $node ? It appears as though JPEG is a directory within the same directory that this PHP file is. Is this true? – abelito Jan 04 '12 at 18:21
  • $node is a array loaded by the cms ie drupal. It holds all the data info. JPEg is the dir which holds all the images but the script is loaded by index.php – Vishal Khialani Jan 04 '12 at 19:00

1 Answers1

2

Why you are not using json_encode

<?php
 $data = array( );
 foreach (glob($queryglob) as $filename) $data[$filename] = array( 'caption' => '' );
?>
<script type="text/javascript">
 var data = <?php echo json_encode( $data ); ?>
</script>

That is much more clever than building a string

SergeS
  • 11,533
  • 3
  • 29
  • 35