For example I have a PHP array, such as this one
<?php $s= array('a','b','c','d','e','f') ; ?>
And I need to loop through it in JavaScript, any ideas how do I do that?
for ( i=0 ; i < <?php echo sizeof($s) ?> ; i++) {
document.write('<?php echo $s [somehow need to get the 'i' value into here] ?>');
}
Any suggestions? Thanks!
Before your ehco/print or else your php array we make sure it's in JavaScript syntax.
<?php
$s=array('a','b','c','d','e','f');
$s_to_json=json_encode((array)$s);
?>
<script type="text/javascript">
var fromPHP=<? echo $s_to_json ?>;
for (i=0; i<fromPHP.length; i++) {
yourValue=fromPHP[i];
}
</script>
<?php
$s= array('a','b','c','d','e','f') ;
?>
<?php foreach($s as $a){ ?>
document.write('<?=$a?>');
<?php } ?>
Not tested but thats one way.
Javascript and PHP cannot be combined. They are two completely different programs that communicate only vaguely. The PHP runs on the server computer and generates the HTML. The javascript runs on the client computer in the webbrowser and acts on that HTML. If you need to move information from PHP into Javscript somehow, then you have to store it in the HTML and have the Javascript access it through that HTML. If you need to do the reverse, move information from Javascript to PHP, have the Javascript call a PHP page with a query string.
One way to place the information in your array somewhere where Javascript can get to it, would be to echo it into a hidden div. Either in a series of ided spans or just a comma separated list. Then you can pull it out of the DOM.
For example:
<div style="display: none;" id="myArray">
<?php
echo '<span id="myArray.count">'.sizeof($s).'</span>';
for ($i = 0; $i < sizeof($s); $i++) {
echo '<span id="myArray.'.$i.'">'.$s[$i].'</span>';
}
?>
</div>
Then in the Javascript you can access the array in the DOM:
var myArray = new Array();
for(i = 0; i < document.getElementById('myArray.count').innerHTML; i++) {
document.write(document.getElementById('myArray.'+i).innerHTML);
}
Disclaimer: untested code, and I don't have the time to perfect it right now. If someone else wants to comment or edit to fix any errors feel free :)
Yes.... echo out your PHP array as a JavaScript array first, and then loop over that. Don't try looping over your PHP array; you can't.
<?php $product = array('1'=>'acids','2'=>'chemical','3'=>'microbilogy'); ?>
<script>
<select name="product_id" class="form-control">
<?php foreach ($product as $key => $value)
{ echo" <option value=$value[product_id]> $value['product_name']
</option>"; } ?>
</select>
</script>
if this is helpfull please give a thumbs up
Actually you can do it, if you reverse the priority from JavaScript being the base, to PHP being the loop base.
<?php
$s= array('a','b','c','d','e','f') ;
for ( $i=0 ; $i < sizeof($s); i++)
{
?>
<script type="text/javascript">
document.write('<?php echo $s[$i]?>');
</script>
<?php
}
Related
Could anybody help me with this little issue. Im trying to change the class of a page number if clicked. but im trying through a js function call using a dynamic php ID . The code below should show you what i mean, Basically the function would change the class of the selected number.
echo"
<div class='pagebuttonsdiv'>";
for ( $x =0 ; $x < $pagesnum ; $x++ ) {
$pagex=$x+1;
if ($pagex<1) {$pagex==1;}
if ($pagex>$pagesnum) {$pagex==$pagesnum;};
if ($x > $pagesnum) {$x==$pagesnum;}
echo "
<div id='{$x}' class='pagebuttons' onclick='pageclick({$x},
{$display}, {$maxresults} , {$startfrom});'>
{$pagex}</div>";
if ($x==$ifclicked) {?>
<script type="text/javascript">
document.getElementById({$x}).className =
'pagebuttonsclicked';}
</script>
<?php
};
};
echo"
</div>
";
Anybody have any idea how i should go about this, Many thanks in advance.
<div id="id[<?php echo $x; ?>]" class="pagebuttons" onclick="pageclick(<?php echo$x; ?>)">
{$pagex}</div>
Not sure why are you sending all those variables in function. you just need the id to change that.
Simple Answer -
echo"
";
for ( $x =0 ; $x < $pagesnum ; $x++ ) {
$pagex=$x+1;
if ($pagex<1) {$pagex==1;}
if ($pagex>$pagesnum) {$pagex==$pagesnum;};
if ($x > $pagesnum) {$x==$pagesnum;}
echo "
<div id='{$x}' class='pagebuttons' onclick='pageclick({$x},{$display}, {$maxresults} , {$startfrom});'>
{$pagex}</div>";
if ($x==$ifclicked) { echo " <script> document.getElementById({$x}).className='pagebuttonsclicked' </script> ";};
};
echo"
</div>
<br>
";
call the function from php to change class. = onlclicking the number, it changes its class to change whatever you wish it to change according to the new css class... I changed the border surround color...
I usually echo script alert by simply
echo '<script type="text/javascript">alert("'.$my_message.'");</script>';
but how to echo the script when the script contains php tags? (see my example code)
Because of my php obfuscator script, I have to use only one <?php ?> tag. so in this case I need to echo the javascript without having <?php tags. What are the possible solutions in this case?
<?php
...some php code...
<script type="text/javascript">
jQuery(document).ready(function($){
$i = 0;
$('.wrapper_vertical_menu .megamenu_menu').append('<div class="more-wrap"><span class="more"><?php echo $this->__("More"); ?></span></div>');
$('.wrapper_vertical_menu .megamenu_menu > li.megamenu_lv1').each(function(){
$i ++;
if($i>13){
$(this).css('display', 'none');
}
});
... more js code ...
JavaScript doesn't "contain PHP tags". All your PHP code needs to do is build the resulting output string (which happens to be JavaScript code, but that doesn't matter to PHP) and echo it.
So where you have something like this:
echo "some javascript code <?php echo some_php_value; ?> more javascript code";
What you really want, quite simply, is this:
echo "some javascript code " . some_php_value . " more javascript code";
Don't try to nest <?php ?> tags within each other. Just concatenate the actual output you want and echo that output.
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";
}
?>
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] = '<img src="../images/'+ j +'.jpg" border="0">';
}
echo "leftrightslide[".$i."]='<img src=\"../images/".$j.".jpg\" border=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
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";
}
?>
I am new to php and I am trying to create a simple bit of code that prints a "last" class at the start of the last element in a "while" loop. There are only two items in the loop (blog excerpts) hence why I have tried below with the if ($i == 1)... Thanks for any help.
Here is my code so far - which only returns the p
<?php
$i = 0;
if($i == 1) {
echo '<p class="last">';
}
else {
echo '<p>';
}
?>
EDIT:
Thanks for the help so far. Greatly appreciated - I have provided a bit more information below (I posted late at night, so I realise I haven't been all that clear).
This is the full piece of code I am trying to write. It is pulling blog excerpts from Wordpress - currently limited to 2 blog articles.
<?php
$posts = new WP_Query('showposts=2');
while ( $posts->have_posts() ) : $posts->the_post();
?>
<p><?php echo the_title(); ?><br/>
<?php echo substr(get_the_excerpt(), 0,200); ?>... Read More</p>
<?php endwhile; ?>
<?php wp_reset_query(); ?>
I am wanting to add the class "last" to the p at the start of line 5 - for the last blog except only.
Thanks again.
Nick's answer says almost all that needs to be said.
The only thing I might add is a slight variation to save duplication particularly if the the contents of your paragraph tags is more complicated.
This might be better done with the following tweak on Nick's code:
<style>
#contents p:last-child {
PUT CONTENTS OF CLASS HERE
}
</style>
<body>
<div id="#contents">
<?php
$numLoops = 2;
$ctext=""
for($i=0; $i<$numLoops; $i++) {
$info="whatever";
if($i == (numLoops-1)) {
$ctext=' class="last"';
}
echo "<p${ctext}>${info}</p>\n";
}
?>
</div>
</body>
Cheers
So you have two paragraphs, and you want to apply the class "last" to the last one? Sounds like this is better handled with CSS
<style>
#contents p:last-child {
PUT CONTENTS OF CLASS HERE
}
</style>
<body>
<div id="#contents">
<p> first info</p>
<p> last info </p>
</div>
</body>
OR if you want to learn about loops
<?php
$numLoops = 2;
for($i=0; $i<$numLoops; $i++) {
if($i == (numLoops-1)) {
echo '<p class="last">';
} else {
echo '<p>';
}
}
What we are doing here with the for loop is initially setting the variable $i=0; then setting a test that says keep looping as long as the variable is less than the number of loops we want do do. Next we are setting what to do each loop, in this case we increment our variable by one each time.
First loop
i=0, we see that 0 is < 2 so we continue
Second loop
We execute the $i++ so we increment $i by 1 from 0 to $i=1,
we test and see $i=1 is still less than 2 so we continue.
Third attempted loop
We increment $i by 1 and get $i=2.
We test to see if this is less than 2, but it is NOT so we do not execute code in the loop
The main issue is that you don't have a loop in your code, and if you did you aren't incrementing your variable $i
I am trying to get desks highlighted that are available based off of a form that asks for the the day, time start and time end. I am able to echo out all the desks that are available, but I cant get the jquery to work with it.
foreach ($allData as $desk => $id){
foreach ($id as $computer){?>
<div id="<?php echo $desk?>"></div><?php
}
}
<style>
.availableDesk{
background: #000000
}
</style>
<script>
$(document).ready(function() {
jQuery( " <?php echo $desk ?> " ), addClass('availableDesk') ;
})
</script>
DESKS:
<ul class="tabs">
<li id="1A"><div id="ddesk"></div></li>
<li id="1B"><div id="ddesk"></div></li>
<li id="1C"><div id="ddesk"></div></li>
</ul>
You're missing the ?> at the end of your PHP block.
<?php
foreach ($allData as $desk => $id){
foreach ($id as $computer){?>
<div id="<?php echo $desk?>"></div><?php
}
} // You need a "?>" here
?>
There are a few things wrong with your jQuery code. First off, if $desk is an ID, you need to do $('#ID'). Second, you have a comma before addClass instead of a period.
jQuery("#<?php echo $desk ?>").addClass('availableDesk');
P.S. HTML ID's aren't supposed to start with a number. Also, you cannot have multiple elements with the same ID, I suggest you use classes instead.
I can see a couple of potential issues here...
jQuery( "<?php echo $desk ?>" ), addClass('availableDesk') ;
Syntactically, I think this should be:
jQuery("#<?php echo $desk ?>").addClass('availableDesk');
Note the # in the selector, this tells jQuery that you are looking for an id. The addClass method is available on the returned items, so you need a stop (.) not a comma (,)
The other gotcha is that you are writing the id in a foreach loop in PHP - I presume that each desk has a unique id - when you write jQuery("#<?php echo $desk ?>") the statement is outside of the foreach loop, so it won't match the ids you are targeting.
If you know that the desk is available in PHP, the best option would be to set the class as you write the desk...
<div id="<?php echo $desk?>" class="availableDesk"></div>