Is it possible to run javascript code within a php loop?
the javascript works perfect the problem is that it is currently not executing more than once.
while(...) {
$l=$l+1;
$linha="#x".$l;
$linha2="x".$l;
?>
<script type="text/javascript">
$(document).ready(function () {
var mensagem = "<?= $mensagem ?>";
var id= "<?= $linha ?>";
var nextMsgOptions = {
msg: mensagem,
side: "bottomMiddle",
CSSClass: "nextMsg-LightTheme",}
$(id).click(function(){
$(id).nextMsg(nextMsgOptions);
});
});
</script>
}
any ideas? 😉
Yes you can output javascript within a PHP loop, to be executed by the browser, when the page loads.
The problem here is that you’ve got tons of variables colliding. You need to encapsulate each output of that script tag in order to keep that from happening. Here’s one suggestion:
This keeps each
$linhaand$mensagemvariable scoped away from each other for each iteration of the loop. What I think is/was happening is in your old code, you’d set$linhato some variable, and outputid = <?= $linha; ?>however many times your loop executed. When$(document).ready()executed for each output,$linhahad already been interpreted to be the last value that you loop output. This causeddocument.readyto attach an event N times (N = number of iterations of your while loop) to the same DOM element (whichever the last iteration of your while loop output$linhato be). With the above snippet, it keeps eachidand$linhavariable scoped away and private from each other, so you shouldn’t have to worry about collisions.I realize that explanation is kind of convoluted and might be hard to grok; but javascript interpretation/execution/scoping has special rules that aren’t incredibly simple to convey without examples.