1

Possible Duplicate:
Reference: Why does the PHP code in my Javascript not work?

This is my attempt to go through an array of pictures.

$rows2 is an array of pictures. I can manually

     echo '<img src="' . $rows2[0] . '"/>';

or

     echo '<img src="' . $rows2[1] . '"/>';

or

     echo '<img src="' . $rows2[2] . '"/>';

and that works fine. So, I added a javascript button and an alert button for testing.

I can see that the var is change from 0 to 1 to 2 however, no picture appears at any point.

<div class="half" id="right">
<?
     echo '<img src="' . $rows2["<script>document.write(counter)</script>"] . '"/>';


?>
<button onclick="counter++">Increment</button>
<button onclick="counter--">Decrement</button>
<button onclick="alert(counter)">alert</button>

</div>

what am I doing wrong?

Community
  • 1
  • 1
Cripto
  • 3,581
  • 7
  • 41
  • 65

1 Answers1

2

I think you have a misunderstanding about how Javascript and PHP interact. Your PHP will be run and sent to the client. The clients browser will recieve this:

<div class="half" id="right">
<img src=""/>
<button onclick="counter++">Increment</button>
<button onclick="counter--">Decrement</button>
<button onclick="alert(counter)">alert</button>
</div>

Note that src is empty because (presumably) $rows2 doesn't have a value with key <script>document.write(counter)</script>

You'll have to rework the code so that the Javascript already has all the information it needs (i.e. by writing an array of images into the javascript).

Jim
  • 22,354
  • 6
  • 52
  • 80
  • If I understand correctly, hand off all of the echo ''; into an array in JS and have it write out the entire thing? in side my php tags? – Cripto Dec 19 '12 at 17:50
  • @user1048138 Pretty much. Then the js will have an array of image sources so when the button is clicked the js can grab the next source and update the image src. – Jim Dec 19 '12 at 19:46