javascript within php loop - php

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:
<script type="text/javascript">
<?php while(...): $l++; $linha = "#x" . $l; $linha2 = "x" . $l; ?>
(function($)
{
var mensagem = "<?= $mensagem; ?>",
id = "<?= $linha; ?>",
nextMsgOptions = {
msg: mensagem,
side: "bottomMiddle",
CSSClass: "nextMsg-LightTheme"
};
$(document).ready(function() {
$(id).click(function(){
$(id).nextMsg(nextMsgOptions);
});
});
})(jQuery);
<? endwhile; ?>
</script>
This keeps each $linha and $mensagem variable 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 $linha to some variable, and output id = <?= $linha; ?> however many times your loop executed. When $(document).ready() executed for each output, $linha had already been interpreted to be the last value that you loop output. This caused document.ready to 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 $linha to be). With the above snippet, it keeps each id and $linha variable 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.

Yes you can:
<? while(...) { ?>
<script type="javascript">
// Here is you're js code
</script>
<? } ?>
it's be very hard to add in each container php tags.

Related

running javascript from php?

I don't know if this is possible as i know php is server side and javascript is client side.
But i am trying to run this javascript code from an if isset inside a php page.
I am using this code:
<?php
if( isset($_POST['submit2'])){
echo "
<script type=\"text/javascript\">
$(document).ready(function(){
setTimeout(function () {
doWork();
window.location.reload();
}, 2000);
function doWork() {
$('#submit').trigger('click');
}
});
</script>";
}
?>
this javascript should click on the button named (submit) and it works fine if its not inside the PHP echo.. and I also checked to see if the if if( isset($_POST['submit2'])) actually returns a value and it does and it works as it should.
So, I don't know what the issue is here>
can some one please help me out with this?
I have always found it best to keep my main javascript/jquery code within the head tag and use php to check and set variables that allow my scripts to run; echoing a javascript boolean into my JS block using php. This way you know that the javascript is doing what it should natively and not worry about elements not being treated properly in the DOM.
So I would do this (I don't know the order in which you want things to happen so this might seem out of order but the principle should still be the same):
<?php
if( isset($_POST['submit2'])){
$varSet = "var set2 = 1;";
} else {
$varSet = "var set2 = 0;";
}
?>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type=\"text/javascript\">
$(document).ready(function(){
<?php echo $varSet; ?>
if(set2 == 1){
setTimeout(function () {
doWork();
window.location.reload();
}, 2000);
function doWork() {
$('#submit').trigger('click');
}
}
});
</script>
</head>

How To Pass PHP Variable To This Javascript Function?

Let's say I have this PHP variables :
$SelectedCountry = "USA";
$SelectedState = "Texas";
on the other hand, I have this javascript function to display all available countries and states :
function print_country(country_id){
// given the id of the <select> tag as function argument, it inserts <option> tags
var option_str = document.getElementById(country_id);
option_str.length=0;
option_str.options[0] = new Option('Where do you live now?','');
option_str.selectedIndex = 0;
for (var i=0; i<country_arr.length; i++) {
option_str.options[option_str.length] = new Option(country_arr[i],country_arr[i]);
}
}
function print_state(state_id, state_index){
var option_str = document.getElementById(state_id);
option_str.length=0; // Fixed by Julian Woods
option_str.options[0] = new Option('Select state','');
option_str.selectedIndex = 0;
var state_arr = s_a[state_index].split("|");
for (var i=0; i<state_arr.length; i++) {
option_str.options[option_str.length] = new Option(state_arr[i],state_arr[i]);
}
}
my question is... how to make 'USA' and 'Texas' becomes selected <option> which generated by those two javascript functions? thanks.
NOTE #1 : you can see the complete code of javascript here : http://sourceforge.net/projects/countries/files/
NOTE #2 : those function called by adding this line on my PHP :
<script type="text/javascript" src="scripts/countries.js"></script>
<script language="javascript">print_country("country");</script>
so basically I need your help how to pass that PHP variables so that it can be 'received' by javascript function INSIDE that countries.js file.
One way is to just echo out some JavaScript statements:
<script>
<?php
echo "
var SelectedCountry = '$SelectedCountry';
var SelectedState = '$SelectedState';
";
?>
</script>
Then just use them in your loops to check if the option needs to be selected or not.
If you're going to be doing a lot of this sort of thing, though, embedding PHP into JavaScript isn't really the best approach. Read up on AJAX and PHP's json_encode() function.
There are two answers:
1 Use AJAX cal and pass back JSON
$.ajax({
url: '/myScript.php',
success: function(data) {
//Do something
}
});
myScript.php
return json_encode($myVar);
2 Embed PHP into the JavaScript
<script>
var myPHPVariable = <?php echo $myVar; ?>
</script>

Is it possible to insert php variables into your js code? [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
passing variables from php to javascript
I'm dynamically generating a list. I want to make each row hover on mouseover and clickable to a link. I want the link to pass the id of the content of the row.
Basically:
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?$cid');
});
});
</script>
The issue is in the js/jquery. I want to be able to grab the $cid and pass it to the student.php page upon click. The php code above works but the js won't of course. I know the fundamental of client-side vs server-side languages. This question doesn't warrant a lecture. I know I cannot do this exactly, but it is what I want to happen ultimately. Any thoughts on how I can achieve this simply? Thanks in advance my friends!
Yes, if you include the <script> section in your PHP code, you can do something similar to the following:
<script>
var foo = <?php echo $foo; ?>;
</script>
In your case, you would be looking into the following code structure:
<script>
$(function () {
$('#rc_desc<?php echo $cid ?>').hover(function () {
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid ?>').click(function () {
$(location).attr('href', 'student.php?<?php echo $cid ?>');
});
});
</script>
The reason why this is possible is because although the Javascript is run on the client-side, it's processed on the server-side first prior to being presented on the page. Thus, it'll replace all necessary instances of $cid with the one you have included.
Enjoy and good luck!
EDIT:
<script>
$(function () {
$('.rc_desc').hover(function () {
$(this).toggleClass('.tr ');
});
$('.rc_desc').click(function () {
$(location).attr('href', 'student.php?' + $(this).attr('id').split('rc_desc')[1]);
});
});
</script>
You can do it like this :
$(location).attr('href','<?php echo $cid ?>');
The javascript code doesn't know it comes from php, it appears as a constant (a literal) for it.
Yes it is possible. All you have to do is put your <?PHP echo $cid; ?> in where you need it
<script>
$(function ()
{
$('#rc_desc<?PHP echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc$cid').click(function ()
{
$(location).attr('href','student.php?<?PHP echo $cid; ?>');
});
});
This is possible because by the time the scrip is put into the page the cid has already been replaced by the string on the server. Since PHP is server driven, before it spits back the html/script it will be just like you put it in yourself.
There is almost no way to actually communicate PHP and JavaScript. However, the best and simplest way is to set the ID within an attribute. The new HTML5 data attributes would be perfect.
For example, have a anchor tag with
<span data-id="22">some event</a>
and then:
$(this).attr('href','student.php?'+$(this).attr('data-id'));
Or just use
<?php echo $id; ?>
if it is not external JS file
Try this code
foreach ($courses as $cid=>cinfo){
$univ = $cinfo['univ'];
$desc = $cinfo['desc'];
$size = $cinfo['size'];
$start = $cinfo['start'];
print "<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
}
<script>
$(function ()
{
$('#rc_desc$cid').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
$(location).attr('href','student.php?' + $(this).attr("data-id"));
// if you want to redirect the page do this
// window.location.href = 'student.php?' + $(this).attr("data-id");
});
});
</script>
I think you block should be :
<script>
$(function ()
{
<?php foreach($courses as $cid=>cinfo) : ?>
$('#rc_desc<?php echo $cid; ?>').hover(function ()
{
$(this).toggleClass('.tr');
});
$('#rc_desc<?php echo $cid; ?>').click(function ()
{
$(location).attr('href','student.php?<?php echo $cid; ?>');
});
";?>
<?php endforeach; ?>
});
</script>
UPDATE
But you don't really need to do this, you have
"<div class='rc_desc' data-id='$cid' id='rc_desc$cid'>"."$desc<br/>"."<b>$univ</b><br/>".
"<span>Number of students</span>: $size<br/>".
"<span>Started at</span>: ".date('F d, Y',strtotime($start))."<br/>".
You can try this
$(function (){
$('.rc_desc').hover(function ()
{
$(this).toggleClass('.tr');
});
$('.rc_desc').click(function ()
{
attrId = $(this).attr("data-id");
$(location).attr('href','student.php?'+id);
});
});

Jquery .each method

learning Jquery and integrating with PHP - getting there, but have one last challenge in some code I'm working on.
I have HTML in a string, trying to pull html in tags, might be multiple elements in the HTML string, so trying to use each. My function worked fine without each, below is my each integration (returns nothing currently):
<?php
$info = '<li><strong>I want this text</strong></li><li><strong>I want this text too</strong></li>';
$info = json_encode($info);
?>
<script type="text/javascript">
$(document).ready(function () {
$("a", $( < ? php echo $info; ? > )).each(
function () {
alert($(this).html());
});
};
This code below does work, but only returns the first element in the HTML:
<?php
$info = '<li><strong>I want this text</strong></li>';
$info = json_encode($info);
?>
<script type="text/javascript">
$(document).ready(function () {
var output = $("a", $( < ? php echo $info; ? > )).html();
var link = $("a", $( < ? php echo $info; ? > )).attr("href");
alert(output);
alert(link);
});
</script>
This is a description and a working example of How to use .each() LINK
You can try this one as a example
$("a").each(function(index){alert($(this).html()});
Your code is not working because there are a few syntax issues.
First, change
< ? php echo $info; ? >
to
<?php echo $info; ?>
PHP doesn't like spaces and the opening and closing tags must appear without spaces.
Second, close the ready function and the script tag properly. Instead of
};
use,
});
</script>
Why are you encoding a piece of XML with JSON? That makes like no sense at all. Both are ways to encode data. HTML is XML too, btw. You can directly reference the $info variable since PHP will process everything first on the server.
<?php
$info = '<li><strong>I want this text</strong></li>';
?>
<script type="text/javascript">
$(document).ready(function() {
$("a", $("<?php echo $info; ?>")).each(
function () {
alert($(this).html());
}
);
});
Or just remove the temporary variable altogether. Makes it combersome to read, but that's essentially what PHP is doing.
$("a", $("<?php echo '<li><strong>I want this text</strong></li>'; ?>")).each(
Or to make it even simpler, since you already have the HTML, simply include it as part of the page and maybe give it an ID to make referencing it easier with jQuery.
<li id="myList">
<strong>I want this text</strong>
</li>
<script type="text/javascript">
$(document).ready(function() {
$("a", "#myList").each(function() {
alert($(this).html());
});
});
</script>
This last example gets rid of PHP completely, but you weren't really using it anyways.

How to access PHP session variables from jQuery function in a .js file?

How to access PHP session variables from jQuery function in a .js file?
In this code, I want to get "value" from a session variable
$(function() {
$("#progressbar").progressbar({
value: 37
});
});
You can produce the javascript file via PHP. Nothing says a javascript file must have a .js extention. For example in your HTML:
<script src='javascript.php'></script>
Then your script file:
<?php header("Content-type: application/javascript"); ?>
$(function() {
$( "#progressbar" ).progressbar({
value: <?php echo $_SESSION['value'] ?>
});
// ... more javascript ...
If this particular method isn't an option, you could put an AJAX request in your javascript file, and have the data returned as JSON from the server side script.
I was struggling with the same problem and stumbled upon this page. Another solution I came up with would be this :
In your html, echo the session variable (mine here is $_SESSION['origin']) to any element of your choosing :
<p id="sessionOrigin"><?=$_SESSION['origin'];?></p>
In your js, using jQuery you can access it like so :
$("#sessionOrigin").text();
EDIT: or even better, put it in a hidden input
<input type="hidden" name="theOrigin" value="<?=$_SESSION['origin'];?>"></input>
If you want to maintain a clearer separation of PHP and JS (it makes syntax highlighting and checking in IDEs easier) then you can create JQuery plugins for your code and then pass the $_SESSION['param'] as a variable.
So in page.php:
<script src="my_progress_bar.js"></script>
<script>
$(function () {
var percent = <?php echo $_SESSION['percent']; ?>;
$.my_progress_bar(percent);
});
</script>
Then in my_progress_bar.js:
(function ($) {
$.my_progress_bar = function(percent) {
$("#progressbar").progressbar({
value: percent
});
};
})(jQuery);
You can pass you session variables from your php script to JQUERY using JSON such as
JS:
jQuery("#rowed2").jqGrid({
url:'yourphp.php?q=3',
datatype: "json",
colNames:['Actions'],
colModel:[{
name:'Actions',
index:'Actions',
width:155,
sortable:false
}],
rowNum:30,
rowList:[50,100,150,200,300,400,500,600],
pager: '#prowed2',
sortname: 'id',
height: 660,
viewrecords: true,
sortorder: 'desc',
gridview:true,
editurl: 'yourphp.php',
caption: 'Caption',
gridComplete: function() {
var ids = jQuery("#rowed2").jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var cl = ids[i];
be = "<input style='height:22px;width:50px;' `enter code here` type='button' value='Edit' onclick=\"jQuery('#rowed2').editRow('"+cl+"');\" />";
se = "<input style='height:22px;width:50px;' type='button' value='Save' onclick=\"jQuery('#rowed2').saveRow('"+cl+"');\" />";
ce = "<input style='height:22px;width:50px;' type='button' value='Cancel' onclick=\"jQuery('#rowed2').restoreRow('"+cl+"');\" />";
jQuery("#rowed2").jqGrid('setRowData', ids[i], {Actions:be+se+ce});
}
}
});
PHP
// start your session
session_start();
// get session from database or create you own
$session_username = $_SESSION['John'];
$session_email = $_SESSION['johndoe#jd.com'];
$response = new stdClass();
$response->session_username = $session_username;
$response->session_email = $session_email;
$i = 0;
while ($row = mysqli_fetch_array($result)) {
$response->rows[$i]['id'] = $row['ID'];
$response->rows[$i]['cell'] = array("", $row['rowvariable1'], $row['rowvariable2']);
$i++;
}
echo json_encode($response);
// this response (which contains your Session variables) is sent back to your JQUERY
You cant access PHP session variables/values in JS, one is server side (PHP), the other client side (JS).
What you can do is pass or return the SESSION value to your JS, by say, an AJAX call. In your JS, make a call to a PHP script which simply outputs for return to your JS the SESSION variable's value, then use your JS to handle this returned information.
Alternatively store the value in a COOKIE, which can be accessed by either framework..though this may not be the best approach in your situation.
OR you can generate some JS in your PHP which returns/sets the variable, i.e.:
<? php
echo "<script type='text/javascript'>
alert('".json_encode($_SESSION['msg'])."');
</script>";
?>
This is strictly not speaking using jQuery, but I have found this method easier than using jQuery. There are probably endless methods of achieving this and many clever ones here, but not all have worked for me. However the following method has always worked and I am passing it one in case it helps someone else.
Three javascript libraries are required, createCookie, readCookie and eraseCookie. These libraries are not mine but I began using them about 5 years ago and don't know their origin.
createCookie = function(name, value, days) {
if (days) {
var date = new Date();
date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
var expires = "; expires=" + date.toGMTString();
}
else var expires = "";
document.cookie = name + "=" + value + expires + "; path=/";
}
readCookie = function (name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
eraseCookie = function (name) {
createCookie(name, "", -1);
}
To call them you need to create a small PHP function, normally as part of your support library, as follows:
<?php
function createjavaScriptCookie($sessionVarible) {
$s = "<script>";
$s = $s.'createCookie('. '"'. $sessionVarible
.'",'.'"'.$_SESSION[$sessionVarible].'"'. ',"1"'.')';
$s = $s."</script>";
echo $s;
}
?>
So to use all you now have to include within your index.php file is
$_SESSION["video_dir"] = "/video_dir/";
createjavaScriptCookie("video_dir");
Now in your javascript library.js you can recover the cookie with the following code:
var videoPath = readCookie("video_dir") +'/'+ video_ID + '.mp4';
I hope this helps.
Strangely importing directly from $_SESSION not working but have to do this to make it work :
<?php
$phpVar = $_SESSION['var'];
?>
<script>
var variableValue= '<?php echo $phpVar; ?>';
var imported = document.createElement('script');
imported.src = './your/path/to.js';
document.head.appendChild(imported);
</script>
and in to.js
$(document).ready(function(){
alert(variableValue);
// rest of js file

Categories