I have two $_SESSION variables impossible to access in any script of my page but it's sure they exist in the PHP code of the same page when I use echo to display their values.
I can display in jQuery every classical PHP variables I want with the following code, but it's impossible when they are $_SESSION variables :
<?php if( isset($_SESSION['id']) ){
echo $_SESSION['id']; // it displays the value
} ?>
<script type="text/javascript">
$(document).ready(function() {
$("#some_button").click(function(){
var a = <?php echo $_SESSION['id']; ?>;
alert(a);
});
});
</script>
I don't understand why honestly...
If you are using PHP 5.2.0 or later, change this:
var a = <?php echo $_SESSION['id']; ?>;
To this:
var a = <?php echo json_encode($_SESSION['id']); ?>
That will put quotation marks around the result if necessary and escape characters for JavaScript as needed.
If you want to use something earlier than PHP 5.2.0, you can do something like this:
var a = '<?php echo $_SESSION['id']; ?>'
Ideally, though, you'd want to use a regexp and/or escaping/replacing functions unless you know that $_SESSION['id'] will only have safe characters. json_encode() has that stuff baked in already, so it's preferable.
I don't know if the example is in the same page but i suspect you 're missing session_start() so you can't use session variables
It is working to me:
Ready and test the code below, it is quite similar to your code, but I think you forgot to call jquery api.
<?php>
session_start();
$_SESSION['id'] = 1;
if ( isset($_SESSION['id']) )
{
echo $_SESSION['id'];
echo json_encode($_SESSION['id']);
}
?>
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script type="text/javascript">
$(document).ready(function()
{
$("#some_button").click(function(){
var a = "Result: "+ <?php echo json_encode($_SESSION['id']); ?>;
//var a="<?php echo $_SESSION['id']; ?>";
alert(a);
});
});
</script>
<form method="post" name="form" action="#">
<input type="submit" id="some_button" value="Clique" />
</form>
If its a string:
var a= "<?php echo $_SESSION['id']; ?>";
Related
I am trying to call JavaScript function with parameter that are PHP variables.
I have tried 2 approaches.
calling JavaScript function in PHP with script tags in echo
i.e
<?php
echo '<script>initialize('.$lat.','.$lang.','.$zom.');</script>';
?>
assigning PHP variables values to JavaScript variables
<script>
var lat="<?php echo $lat;?>";
var lang="<?php echo $lang; ?>";
var zoom="<?php echo $zoom; ?>";
alert(lat+lang+zoom);
initialize(lat,lang,zoom);
</script>
In first case function is called as I cross-checked from page source but parameters passed are undefined.
And in 2nd case values are successfully saved in JavaScript variables, check it by alert(), but function is not called.
Here is the whole code:
<!DOCTYPE html>
<html>
<head>
<script src="http://maps.googleapis.com/maps/api/js?key=AIzaSyDY0kkJiTPVd2U7aTOAwhc9ySH6oHxOIYM&sensor=false">
</script>
<?php
if( isset($_POST['lat']) && isset($_POST['lang']) && isset($_POST['zoom']) && isset($_POST['city'])):
$lat=$_POST['lat'];
$lang=$_POST['lang'];
$zoom=$_POST['zoom'];
$city=$_POST['city'];
$zom=(int)$zoom;
var_dump($lang);
var_dump($lat);
//var_dump($zoom);
var_dump($zom);
//echo '<script>initialize('.$lat.','.$lang.','.$zom.');</script>';
endif;
?>
<script>
var lat="<?php echo $lat; ?>";
var lang="<?php echo $lang; ?>";
var zoom="<?php echo $zoom; ?>";
alert(lat+lang+zoom);
initialize(lat,lang,zoom);
</script>
<script>
function initialize(a,b,zom){
if (!a || !b ||!zom){
alert('came on not' +a+b +zom);
// var centerLoc=new google.maps.LatLng( 33.61701054652337,73.37824736488983);
zoom=16;
}
else
{
alert('came');
var zoom =parseInt(zom);
var centerLoc=new google.maps.LatLng(a,b);
}
var mapProp = {
center:centerLoc,
zoom:zoom,
//mapTypeId:google.maps.MapTypeId.ROADMAP
mapTypeId:google.maps.MapTypeId.SATELLITE
};
var map=new google.maps.Map(document.getElementById("googleMap") ,mapProp);
marker=new google.maps.Marker({
position:centerLoc,
title:'Click to zoom'
});
google.maps.event.addListener(marker,'click',function() {
map.setZoom(map.getZoom()+1);
map.setCenter(marker.getPosition());
});
marker.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body style= "background-color:gainsboro;">
<form method="POST" action="myPage.php" >
Enter latitude: <input type ="text" name="lat" id="lat" / ><br/>
Enter longitude: <input type ="text" name="lang" id="lang"/ ><br/>
Enter City Name: <input type="text" name="city" id="city"/><br/>
Enter Zoom level: <input type ="text" name="zoom" id="zoom"/ ><br/>
<input type="button" value ="Perview" onclick=" initialize(
document.getElementById('lat').value,
document.getElementById('lang').value,
document.getElementById('zoom').value)"/>
<input type="Submit" value="Save" />
</form>
<center><div id="googleMap" style="width:1000px;height:500px;"></div></center>
</body>
</html>
Use json_encode(). If you don't there will always be the possibility you escaped your data incorrectly as it passes from the PHP to the HTML/JS layer.
$vars = array($lat, $lang, $zoom);
// JSON_HEX_TAG and JSON_HEX_AMP are to remove all possible surprises that could be
// caused by vars that contain '</script>' or '&' in them. The rules for
// escaping/encoding inside script elements are complex and vary depending
// on how the document is parsed.
$jsvars = json_encode($vars, JSON_HEX_TAG | JSON_HEX_AMP);
echo "<script>initialize.apply(null, $jsvars)</script>";
In general, for your sanity, all data that is in PHP that you need to make available to js running on the current page should be collected into a single PHP array and then placed into a single js object. For example:
<?php
$jsdata = array(
'formvars' => array(
'lat' => $lat,
'lang' => $lang,
'zoom' => $zoom
),
'username' => $username,
'some_other_data' => $more stuff
);
?>
<script>
var JSDATA = <?=json_encode($jsdata, JSON_HEX_TAG | JSON_HEX_AMP )?>;
initialize(JSDATA.formvars.lat, JSDATA.formvars.lang, JSDATA.formvars.zoom);
</script>
Now there is only a single point of contact between the JS and PHP/HTML layers so you can easily keep track of what you are putting into the JS namespace.
Call the function when the browser finished loading the javascript.
<script>
window.onload = function() {
var lat="<?php echo $lat; ?>";
var lang="<?php echo $lang; ?>";
var zoom="<?php echo $zoom; ?>";
alert(lat+lang+zoom);
initialize(lat,lang,zoom);
};
</script>
Just call on the predefined java script code like jsFunction() ; in your php code
I found some really good examples on Calling a javascript function from php and it appears you can also run the code online at PhpFiddle.org
Just in case the links break, here are the examples:
Example 1: Calling without parameters
<?php
echo "<a href='http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/'>Full example at: http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/</a>";
echo "<p>Add whatever PHP you want here...</p>";
?>
<!--This JS function can be defined here or a separate file since so long as it gets created in JS space'-->
<script>
function callAlert(){
alert('A alert without a parameter');
}
</script>
<script>
callAlert();
</script>
<?php
?>
Example 2: Calling with a single parameter
<?php
echo "<a href='http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/'>Full example at: http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/</a>";
echo "<p>Add whatever PHP you want here...</p>";
//Data that is going to be passed into the JavaScript function. Try to keep all vars together so
//that it's easier to track down the php/javascript interaction
$jsdata = 'MyName';
?>
<!--This JS can be here or a separate file since all it's doing is defining a function in the JS space'-->
<script>
function callAlert(text){
alert(text);
}
</script>
<!--This JS must be defined with the php since it's using previously defined php variables -->
<script>
var JSDATA = <?=json_encode($jsdata, JSON_HEX_TAG | JSON_HEX_AMP )?>;
//Prompt using a single var
callAlert(JSDATA);
</script>
<?php
?>
Example 3: Calling using an array of parameters
<?php
echo "<a href='http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/'>Full example at: http://www.hoverdroids.com/2015/06/10/calling-a-javascript-function-from-php/</a>";
echo "<p>Add whatever PHP you want here...</p>";
$myname = 'MyName';
$yourname = 'YourName';
//Data that is going to be passed into the JavaScript function. Try to keep all vars together so
//that it's easier to track down the php/javascript interaction
$jsdata = array(
'input' => $myname,
'array_input' => array(
'name' => $yourname
),
);
?>
<!--This JS can be here or a separate file since all it's doing is defining a function in the JS space'-->
<script>
function callAlert(text){
alert(text);
}
</script>
<!--This JS must be defined with the php since it's using previously defined php variables -->
<script>
var JSDATA = <?=json_encode($jsdata, JSON_HEX_TAG | JSON_HEX_AMP )?>;
//Prompt using a single var in the array
callAlert(JSDATA.input);
//Prompt using a var from a nested array
callAlert(JSDATA.array_input.name);
</script>
<?php
?>
I have a problem how to pass for example $example=1; variable to this jquery like a value in bracket where is 20, 40, 60.....:
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(20);
$("#pb2").progressBar(40);
$("#pb3").progressBar(60);
$("#pb4").progressBar(70);
$("#pb5").progressBar(100);
$("#pb6").progressBar(100);
});
</script>
The main problem is that I want to example string have value from database, so that's why I need to make it outside of script.
If this code is in your .php page...
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo $pb1 ;?>);
$("#pb2").progressBar(<?php echo $pb2 ;?>);
$("#pb3").progressBar(<?php echo $pb3 ;?>);
$("#pb4").progressBar(<?php echo $pb4 ;?>);
$("#pb5").progressBar(<?php echo $pb5 ;?>);
$("#pb6").progressBar(<?php echo $pb6 ;?>);
});
</script>
Where $pb1,$pb2,$pb3,$pb4,$pb5,$pb6 are Integers ..
This is simple:
<?php
//Insert your code to generate the values to $example
$example = ...
?>
// and here is your JS with php code inside it
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo $example; ?>);
$("#pb2").progressBar(<?php echo $example1; ?>);
$("#pb3").progressBar(<?php echo $example2; ?>);
$("#pb4").progressBar(<?php echo $example3; ?>);
$("#pb5").progressBar(<?php echo $example4; ?>);
$("#pb6").progressBar(<?php echo $example5; ?>);
});
</script>
I hope it helps! Good Luck!
If you meant to pass php variable to client to dynamically replace numbers in jquery you can use like code in below
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(<?php echo example; ?>);
});
</script>
First off, having it in your database does not mean you cannot do so in the script. There are in fact several ways to do that. You could have your javascript file be php that generates javascript instead of html, or perhaps easier: you could use inline javscript. However, if you do want to keep the two separated it is still possible:
[..]
<script type='text/javascript'>var percentageDone = <?php echo intval($example) ?>;</script>
<script type="text/javascript">
$(document).ready(function() {
$("#pb1").progressBar(percentageDone);
});
</script>
[..]
I want to know can I convert a php $_POST variable into a jquery variable. I have php variable below:
<?php $postduration = $_POST['durationChosen']; ?>
Can I convert the php variable above into a jquery variable?
Thanks
Yep, of course!
Just write/output your PHP code right into your JavaScript ... block.
Kinda like this:
<script>
var myVar = <? echo $postduration; ?>;
</script>
var durationChosen = "<?php echo $_POST['durationChosen']?>";
<script type="text/javascript">
var postDuration = '<?php echo $_POST['durationChosen']; ?>';
</script>
Just echo it into the Javascript on the page, just like any other dynamic content.
It is simple as...
var myVar = '<? echo $postduration; ?>';
You can convert it into a javascript variable (jquery framework helps with DOM manipulation)
<?php $postduration = $_POST['durationChosen']; ?>
var myVar = '<?php echo $postduration ?>';
delete_define.php has the following code snippet:
<?php
session_start();
?>
<form action="delete_now.php" target="upload_target" onsubmit="return my_func_1();">
<input type="submit" name="my_submit" class="my_submit" value="submit"/>
<iframe id="upload_target" name="upload_target" src1111="#" style="width:0;height:0;border:0px solid #fff;"></iframe>
</form>
<script type="text/javascript">
function my_func_1(){
//alert("from within my_func() =" +<?php echo $_SESSION['my_session']; ?>);
alert(" my_func_1");
return true;
}
function my_func_2(){
alert("my_func_2 =" +<?php echo $_SESSION['my_session']; ?>);
return true;
}
</script>
delete_now.php has:
<?php
session_start();
$_SESSION['my_session']=rand();
?>
<script type="text/javascript">
alert("from within delete_now.php = " +<?php echo $_SESSION['my_session']; ?>);
window.top.window.my_func_2();
</script>
The problem is my_func_2() does not give the same output for the session variable as the alert box in delete_now.php gives.
Why is that?
EDIT: CHANGED THE CODE SAID TO BE IN delete_define.php
That's because when the delete_define.php was loading the Session var was one, then it's become another, but in you JS stored previous value.
You should store session var into JS var, and then in JS in delete_now.php reset it with the fresh value.
How to refresh value from frame and other situations
Add to first php file's JS something like:
var session_var = '<?php echo $_SESSION['my_session']; ?>';
And then in your delete_now.php's JS:
parent.session_var = '<?php echo $_SESSION['my_session']; ?>';
And change function my_func to alert session_var JS variable.
Think so...
Explanation:
Then result page js will be:
function my_func_2(){
alert("my_func_2 = 13513513513513");
return true;
}
So when you call it, whatever is in the $_SESSION is, there will be old, static value.
Overall process description:
Load delete_define.php
Javascript var, containing actual filename initialized
From submits
Script delete_now.php is runing
Javascript var in main window refreshes
You call my_func_2() which use you global JS var, containing fresh filename.
you have assigned random number, so based on the order you run the page will give alert,
if you start from delete_now.php two consecutive alerts will be same . first assign some static value and then check
I'm drawing a complete blank why this isn't working. I can do it with one variable passing through, but not two. When I use actually numbers like getnt(1,2) it works. It's just not working with two PHP variables.
<script type="text/javascript">
function getnt(nid,pnid) {
window.location = "nt.php?nid=" + nid + "&pnid=" + pnid;
}
</script>
<body>
<?php
echo "<a href='#' onclick='getnt($nid,$pnid)'>VIEW</a>";
?>
</body>
I can make the code work with echo "<a href='nt.php?nid=$nid&pnid=$pnid'>VIEW</a>";, but that's no good if I want to add in alerts and javascript commands.
If the ID and pnID are strings, enclose them with brackets like this.
<body>
<?php
echo "VIEW";
?>
</body>
If still not working, You can debug your code
View the source code in browser,
make sure it generates correctly.
Put some alert messages in the
javascript function. Install Firebug
if you have Firefox or see
Javaascript console if you get any javascript errors.
You could always try:
<script type="text/javascript">
function getnt(nid,pnid) {
window.location = "nt.php?nid=" + nid + "&pnid=" + pnid;
}
</script>
<body>
VIEW
</body>
Your question is probably best answered by looking at the rendered HTML source.
In any case, here's how I'd do it using graceful degradation
<script type="text/javascript">
function getnt(element) {
var href = element.href;
var nid = element.getAttribute("data-nid");
var pnid = element.getAttribute("data-pnid");
return true;
}
</script>
<p><a href="nt.php?nid=<?php echo $nid ?>&pnid=<?php echo $pnid ?>"
data-nid="<?php echo $nid ?>"
data-pnid="<?php echo $pnid ?>"
onclick="return getnt(this)">VIEW</a></p>