PHP: calling javascript function with parameters from php - php

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
?>

Related

pass a variable to a JavaScript function [duplicate]

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I have a button in my php page :
<button id="myButton">Delete me</button>
and in that page I have a variable which I want to pass to a JavaScript function, and this is my JS code :
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
How can I do that ?
I think you might be wanting to put a variable through PHP on your button and pass it to your function using jQuery data. Check this out:
<button data-confirmed="<?php echo $confirmed; ?>" id="myButton">Delete me</button>
And in your js:
$(function() {
$('#myButton').on('click', function(e){
// get jquery object access to the button
var $thisButton = $(this);
// this gets that data directly from the HTML
var confirmed = $thisButton.data('confirmed');
if(confirmed) {
//Here I'll use the variable
}
})
});
Basically, you can access variables in javascript using this method if you are interpolating PHP vars directly on the page. If this isn't what you are looking for, please let me know in comments.
<button id="myButton">Delete me</button>
<input type="hidden" name="variable" id="variable" value=2>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {=
alert(document.getElementById('variable').value);
//Here I'll use the variable
}
})
});
You can declare the variable outside the click event like so:
$(function() {
var confirmed = true;
$('#MyButton').confirmOn('click', function() {
if(confirmed) {
// do stuff
}
});
});
Assuming you're talking about passing php variables to Javascript, you can do this when writing to the page, ex:
<?php
$passThis = 'Passing'
?>
<script language="javascript" type="text/javascript">
var sStr = "My name is <?php echo $passThis ?>.";
document.write(sStr);
</script>
You could also get integer values, doing something like
$integerValue = 5;
var int = "<?php echo $integerValue; ?>";
int = parseInt(int);
By modifying this, you could use it to pass more types of variables, so assuming you have something like this:
<?php
$text = 'someText';
?>
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
//Here I'll use the variable
}
})
});
</script>
you could do
<script>
$(function() {
$('#myButton').confirmOn('click', function(e, confirmed){
if(confirmed) {
console.log("<?php echo $text ?>");
}
})
});
</script>
to make Javascript alert 'someText'.

get variable to jQuery from php

this is my variable in setings.php
$error = output_errors($errors);
i want to echo out in my jQuery file 'settings.js'
$('#save_settings').click(function(){
var first_name = $('#first_name').val();
var last_name = $('#last_name').val();
var email = $('#email').val();
$.post('settings.php', { first_name: first_name, last_name: last_name, email: email}, function(data){
$('#show').html('settings saved').fadeIn(500).delay(2000).fadeOut(500);
alert(data);
});
});
If you want to communicate between JavaScript and PHP, the best way is to create a hidden-inputfield in fill in the errors-variable. And then you can read out the value with jQuery.
The inputfield:
<input type="hidden" value="<?php echo $error; ?>" id="errors" />
And the jQuery-Code:
var errors = $("input#errors").val();
You can't place PHP code inside "javascript" file, PHP code must be in PHP file.
The below code can work if it's placed in .php file:
<html>
<head>
<title>javascript test</title>
<script>
var error = '<?php echo $error;?>';
alert(error);
</script>
</head>
<body>
</body>
</html>
I am assuming that your $error will by different depending on the $_POST values.
If your response header is in HTML, then you can do something like this.
// in your JS codes.
$.post('settings.php', function(response) {
$('#show').html(response).fadeIn(500).delay(2000).fadeOut(500);
});
// in your php codes.
<?php if(isset($error)) { echo($error); } else { echo("setting saved"); } die(); ?>
Anything you want in your js from server side has to come as AJAX or JSON response. echo it from your php function and get it as AJAX or JSON in javascript.
$.getJSON('url for the php file', function(data){}
And in the php file just echo the value
see http://php.net/manual/en/function.json-encode.php
Or take a hidden input field and put the value there. You can get that value from js using the 'id' or 'class' attribute

datetimepicker don't want my php-variable

I have a big problem which really confused me the last five hours.
I use datetimepicker.
<?php
$tabname = "frequency";
$datumstart = "'#datumstart".$tabname."'";
?>
<script type ="text/javascript">
$(function(){$(<?php echo $datumstart; ?>).datetimepicker();
</script>
<input type="text" name="datumstart<?php echo $tabname; ?/>
I want to get the value of the input-field with
$(function load() {
var datumstart = $(<? php echo $datumstart; ?>).val(); });
So everytime I want to run the file with this line
var datumstart = $(<? php echo $datumstart; ?>).val(); });
the alert-output of var datumstart is blank.
But with this
var datumstart = $('#datumstartfrequency').val(); });
I get the value!
What can be wrong?
You are missing apostrophes:
$('<?php echo $datumstart; ?>')

Session var not accessible in my script

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']; ?>";

Session variable does not get updated within javascript code

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

Categories