0

I have this JS inside my php code:

echo " for (var i = 0; i<length; i++){
         alert('array[i]');

}";

Assuming all variables were defined and initialized, i'm not getting any output from the alert.

However, if i replace array[i] with array[2], I get that value alerted.

any advice?

3
  • yes length was defined in my php code Commented Jul 24, 2013 at 20:38
  • How do you define array? Commented Jul 24, 2013 at 20:51
  • @MESSIAH none helped. Still not alerting Commented Jul 25, 2013 at 14:16

5 Answers 5

1

Updated variant:

while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { 
  $storeArray[] = $row['DayNum']; 
} 
$length = count($storeArray); 

for($i=0; $i < $length; $i++) { 
    echo "alert(".$storeArray[$i].");";
}
Sign up to request clarification or add additional context in comments.

5 Comments

Tried this before, didn't work. Forgot to mention that the array is actually a php variable being called in the js code
Can you show us what variables you have and how you define them?
while ($row = mysql_fetch_array($result, MYSQL_ASSOC)) { $storeArray[] = $row['DayNum']; } $length = count($storeArray); echo " function test() { for( var i=0; i< $length; i++){ alert('$storeArray[i]'); } } ";
Thanks, it worked! But is there anyway I could include this in a javascript function instead?
Sure. echo "function showAlert() { "; for($i=0; $i < $length; $i++) { echo "alert(".$storeArray[$i].");"; } echo "}";
1

You need a script tag..Its not possible to alert something the way you are doing it.

<script>//write your javascript here</script>

Example:

 <?php
        function alert($myArray) 
        {
            echo '<script type="text/javascript">alert("' . $myArray . '"); </script>';
        }
    ?>

1 Comment

I'm calling the php file using js: <script type="text/javascript" src="load2.php"> </script>
1

Can it be length is not defined and you think it's giving you the array lenght? in that case you should have i < array.length otherwise length is thought to be a variable.

Check also that array[i] being an "array" where you get the values from in the for loop you don't need the '. Just write alert(array[i]);

Comments

0

alert('array[i]') in this part JavaScript not execute array[i] as variable, instead, it prints it as string because its enclosed with single quota, change it to:

echo '<script>';
echo '
for (var i = 0; i<length; i++){
         alert(array[i]);

}
';
echo '</script>';

1 Comment

the arrayp[] is actually a php variable. I forgot to mention that.
0
<?php echo "<script> for(var i=0; i<array.length; i++){alert(array[i]);} </script>"; ?>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.