0

I was trying to generate a Javascript varialbe using php. I am getting the desired result on the source page but it looks like that result is not being processed into the array. Is there any way of doing it using javascript? Here, I'm generating URLs for images that need to be displayed on my website carousel and though a for loop would save me the time of entering every url. The images are also number serially. Since I'm not well versed in javascript can you suggest me a javascript alternative?

var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
    $j=$i+1;
    echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>
1
  • But can we mix them? If we do, am I supposed to follow any guidelines? @dystroy Commented Jul 12, 2013 at 11:36

4 Answers 4

2

You can do it using javascript only. No reason for using PHP here.

var leftrightslide = new Array()
var finalslide = ''; // this line is not really relevant to the question
for (var i = 0; i < 34; i++){
    var j = i + 1;
    leftrightslide[i] = '<a href="#"><img src="../images/'+ j +'.jpg" border="0"></a>';
}     
Sign up to request clarification or add additional context in comments.

Comments

0
 echo "leftrightslide[".$i."]='<a href=\"#\"><img src=\"../images/".$j.".jpg\" border=0></a>';";

1 Comment

Please consider providing a little more context - for those of us who are a little slower off the mark!
0

Here's a snippet of code that I use to move data from PHP To JS

if (isset($javascriptData)) {
    echo "<script>";
    foreach(array_keys($javascriptData) as $jsData) {
        echo "var " . $jsData . " = " . json_encode($javascriptData[$jsData]) . ";\n";
    }
    echo "</script>";
}

I pass in $javascriptData to my view which is an array with the structure array('JS_VAR_NAME' => 'JS_VALUE')

You can then use those variables in any scripts you've added below that

Comments

0

Since your example code contains no script tags, or other HTML elements for that matter, one might assume that this PHP snippet is intended to generate some JavaScript source "file" external to the page in which it is being used.

If that is the case, consider that the following additional line may just fix it:

<?php header( 'Content-Type: text/javascript' ); ?>

var leftrightslide=new Array()
var finalslide=''
<?php for($i=0;$i<34;$i++) {
    $j=$i+1;
    echo "leftrightslide[".$i."]='<a href='#'><img src='../images/".$j.".jpg' border=0></a>'\n";
}
?>

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.