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>
2
  • What is $node ? It appears as though JPEG is a directory within the same directory that this PHP file is. Is this true? Commented Jan 4, 2012 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 Commented Jan 4, 2012 at 19:00

1 Answer 1

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

3
  • wow ! this was fast. I will try it and get back to u guys Commented Jan 4, 2012 at 18:22
  • Hi, I am using the same json_encode but when i print this array it shows [object Object].Any idea? Commented Feb 29, 2012 at 12:32
  • Abhinandan Sahgal: post this as new question please Commented Feb 29, 2012 at 12:34

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.