about pass php variable to javascript [duplicate] - php

This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 8 years ago.
I got a html5 upload script from
http://tutorialzine.com/2011/09/html5-file-upload-jquery-php/
can i pass php variable to js?
in this html5 upload script
the script.js call the post_file.php to upload file
in post_file.php
$rand = time();
i set the rand is the filename
for example uploaded filename: 1331956640.jpg
can i pass this $rand to script.js?
because i can't print the result in php, only can print something in script.js
this is the html5 upload script download link from tutorialzine
enter link description here
sorry my english not good, thank

<script>
var my_javascript_var = <?php echo $rand; ?>
</script>
or
<input id="my_rand_value" type="hidden" value="<?php echo $rand;?>" />
in js do so
var my_javascript_var = $("#my_rand_value").val():

It's not actually about "passing" a variable from PHP to JavaScript.
Remember that PHP is a server-side scripting language, and JavaScript resides on a client's browser.
So, you could actually... write directly any javascript you wish from your PHP script.
Let's say, you've got a $a variable... then you could simply enter it in your javascript code like this :
<script type='text/javascript'>
var a = <?php echo $a; ?>
</script>
However :
If what you mean is to actually use the $a var while the page has loaded, or retrieve the result in some way, WITHOUT reloading, then what you probably need is Ajax.
To use AJAX, I would either suggest :
the jQuery load method
using some ready-made AJAX object

You can do this
<script>
var javascriptvar = <?=$rand ?>
</script>

You dont need to ....
<script>
var rand = new Date().getTime();
</script>
this uses only JavaScript to get the same result

You can do it this way:
<script language="javascript" type="text/javascript" src="your.js"></script>
...
<img src="your_button.gif" />

Related

using javascript in PHP [duplicate]

This question already has answers here:
What is the difference between client-side and server-side programming?
(3 answers)
Closed 9 years ago.
i have this php and js code:
<script type="text/javascript">
function StartScript(script)
{
<?php require("StartScript.php"); ?>
}
</script>
Start
How can i get the "script" from the javascript function onto the end of the php file?
for example rather than:
<?php require("StartScript.php"); ?>
to have:
<?php require("StartScript.php?script=scriptname"); ?>
The full excerpt (provided that StartScript.php at the same level of current page, otherwise add absolute path):
<script src="http://code.jquery.com/jquery-1.10.1.min.js"></script>
<script type="text/javascript">
function StartScript(script) {
jQuery.getScript('StartScript.php?script=' + escape(script));
}
</script>
This will call StartScript.php with the parameter script. StartScript.php will generate the JavaScript code which will be executed in the client browser.
Reference: http://api.jquery.com/jQuery.getScript/
It's impossible to write server-side code (PHP) with a client-side code (Javascript). This will not work unless you use something like Ajax.
Maybe I misunderstood your question but this seems pretty easy...I would include all the js in the php file so the html side of things would have only....
<?
$script = "Page1";
include("StartScript.php");
?>
and the php would be...
<? if ($script == "Page1"){ ?>
function StartScript(script)
{
alert("IN");
}
</script>
<? } ?>
The problem is that you're mixing up the client (JS) and the server (PHP). PHP is executed on the server and produces some HTML which gets sent to the browser ("the client"). Browsers cannot run PHP because it's a server-side language.
You should evaluate what the desired interaction is between the client and the server here. For example, if you just need to execute some PHP to pass data to JavaScript, you can build up a JavaScript object:
<script type="text/javascript">
<?php // include script that gives you back some data, e.g.: ?>
<?php $somePhpData = array('red', 'yellow', 'blue'); ?>
<?php $jsonData = json_encode($somePhpData); ?>
var dataFromPhpScript = <?php echo $jsonData; ?>
// do something with the data
</script>
Otherwise, if you really need JavaScript to trigger a PHP script running, you're essentially doing AJAX. You'll likely want some sort of REST API. The idea is that you expose a URL from PHP that the JavaScript can call:
<script type="text/javascript">
jQuery(document).ready(function() {
function startScript(scriptName, success) {
$.get('/path/StartScript.php?script-name=' + scriptName)
.done(success)
.fail(fail);
}
startScript('name-of-php-script', function(data) {
// trigger some JavaScript that relies on the output of the PHP script
});
});
</script>

sending javascript variable value to php within the same page [duplicate]

This question already has answers here:
How to get JavaScript variable value in PHP
(10 answers)
Closed 9 years ago.
I just want to know if sending value of a javascript to php is possible.
here is the simple code of what i am trying to say.
<script language="javascript" >
var id = "data"
</script>
<?php
$getthevalueofid = var id;
?>
thanks!
Not the way your code sample is structured, no. PHP is a server-side language and Javascript is a client-side language. PHP is out of scope by the time any client-side script executes.
If you need to pass an object from the browser to your server you can use XMLHttpRequest (commonly referred to as AJAX).
To send a Javascript variable back to PHP, you need to do an AJAX request:
<script language="javascript" >
xmlhttp.open("GET","getvalue.php?id="+id,true);
xmlhttp.send();
</script>
And in getvalue.php you'd have:
<?php
$getthevalueofid = $_GET['id'];
?>
No way to do this. Use Ajax to pass javascript variable to php

php constants in a javascript file [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)
I'm working on a project and it's already done, but it needs one more midification and its applying language constants in javascript files.
consider we include a javascript file and in that we have something like this
alert("YOU Have VOTED BEFORE");
easy like that , the script will alert that text
but what if we need to alert a language constant of it :
alert("<?php echo _VOTED_BEFORE?>");
this will be worked only if echo the script like inline of my php codes ...
but, how can we read and include php constants or $vars for a outside JavaScript file ???
For a cleaner structure, I think the best way is to set all the data you get from PHP in one place, i.e. in the HTML you serve via PHP:
<script>
var MyNameSpace = {
config:
something: "<?php echo _VOTED_BEFORE ?>"
}
}
</script>
In the JavaScript file you include afterwards, you can access the value via MyNameSpace.config.something.
This makes it also easier to reuse the message.
There is a way of doing this using a query string in the script path
See my answer here
How to pass variable from php template to javascript
Unfortunately this will break the cache for your js file so weight your options first
<script type="text/javascript" src="script.js?flag=<?php echo _VOTED_BEFORE?>"></script>
for the sake of not writing too much code refer to the link to see how to retrieve the value
Actually, what you had was close to being proper.
<?php
// Valid constant names
define("VOTED_BEFORE", "false");
?>
<script type="text/javascript">
alert("<?php echo VOTED_BEFORE;?>");
</script>
If it's not a PHP file, you cannot include PHP echo functions in it. I suggest that if you want to use a PHP variable in your external js files then declare it as a global in your PHP
file before you reference the external js.
<script type="text/javascript">
var globalvar = '<?php echo _VOTED_BEFORE ?>' ;
</script>
<script type="text/javascript" src="externalfile.js"></script>
Though it's not always a good idea to clutter the global namespace.
You can use cookies to save these constants and read them in via JavaScript or you will have to use AJAX

Passing a PHP Variable in external JS file [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've read lots of thread on here but I am still unable to get a variable passed from PHP to an external JS file and wondered if someone could assist?
In my PHP file I have the following;
<script type="text/javascript">
var pass_this_variable = <?php $company['website']; ?>;
</script>
<script type="text/javascript" src="/js/track.js"></script>
In the JS file I have the following;
document.write('<IFRAME SRC="$company['website']" WIDTH="300" HEIGHT="400"></IFRAME>');
What I am trying to achieve is an IFRAME be opened and populated with what is contained within $company['website']. I know I can just use IFRAME directly in the PHP file, but this isn't what I have been tasked with for my homework. When I do use IFRAME directly in the PHP file it works fine, and if I specify a static URL in the JS file such as http://www.google.com this also works fine.
Can anyone assist? Thanks
EDIT:
Thanks for the answers so far, however I'm still unable to get it working :(
The frame that I have in track.php (or track.js) won't load the url thats specified in $company['website'], yet if I change it to http://www.google.com its working fine. For some reason the $company['website'] value isn't being passed :(
if you want your external javascript to be dynamic you can make it a php file and give the correct header, example:
<script type="text/javascript" src="/js/track.php"></script>
track.php
<?php
// javascript generator
Header("content-type: application/x-javascript");
?>
document.write('<IFRAME SRC="<?php echo $company['website'] ?>" WIDTH="300" HEIGHT="400"></IFRAME>');
PHP file (don't forget echo and quoting):
<script type="text/javascript">
var pass_this_variable = '<?php echo $company['website']; ?>';
</script>
<script type="text/javascript" src="/js/track.js"></script>
JS file (use pass_this_variable instead):
document.write('<IFRAME SRC="'+pass_this_variable+'" WIDTH="300" HEIGHT="400"></IFRAME>');
You should fix this line:
var pass_this_variable = <?php echo $company['website']; ?>;
Adding echo and it should work
JavaScript provides you the functionality of ajax for the purpose of reading the PHP or text files. Why don't you create the HTML iframe inside a PHP file with your variables parsed and then take back the response and "throw" it inside a div.
The code for your PHP file:
$cmp = $company['website'];
echo '<input type="hidden" id="cmp1" name="cmp1" value="' . $cmp . '" />';
The code for your JavaScript (.js) file to get the PHP file value:
var company = document.getElementById('cmp').value;
Call a PHP file inside the JavaScript source. You can find the tutorial here:
http://www.javascriptkit.com/javatutors/externalphp.shtml.
So your code will be like this:
<script type="text/javascript" src="track.php?company=<?php echo $company['website']; ?>"></script>
In the PHP file you can fetch the value through $_GET variable and use it in the iframe. Make sure to sanitize the input.

Access PHP var from external javascript file

I can access a PHP var with Javascript like this:
<?php
$fruit = "apple";
$color = "red";
?>
<script type="text/javascript">
alert("fruit: " + "<?php echo $fruit; ?>"); // or shortcut "<?= $fruit ?>"
</script>
But what if I want to use an external JS file:
<script type="text/javascript" src="externaljs.js"></script>
externaljs.js:
alert("color: " + "<?php echo $color; ?>");
You don't really access it, you insert it into the javascript code when you serve the page.
However if your other javascript isn't from an external source you can do something like:
<?php
$color = "Red";
?>
<script type="text/javascript">var color = "<?= $color ?>";</script>
<script type="text/javascript" src="file.js"></script>
and then in the file.js use color like so:
alert("color: " + color);
You can also access data from php script in Javascript (I'll use jQuery here) like this
Create input hidden field within you php file like this
<input type="hidden" id="myPhpValue" value="<?php echo $myPhpValue ?>" />
in your javascript file:
var myPhpValue = $("#myPhpValue").val();
//From here you can the whaterver you like with you js Value
if(myPhpValue != ''){
//Do something here
}
This will do the job as well :)
What I've seen done is let .js files run through the php interpreter. Which I can not recommend.
What I do recommend is fetching the values through AJAX and have the PHP file return the value to the JS file. Which is a much cleaner method.
First of all you have to understand that no program can actually have access to the other program's variable.
When you realize that, the rest is simple.
You can either set up a js variable in the main file and then include your external js, or make this external js dynamic, generated by PHP as well
What you likely want, is called Asynchronous JavaScript and XML (AJAX): http://www.w3schools.com/ajax/default.aspa
Basically, imagine being able to send messages from the clients JavaScript to your PHP scripts on the server. In the example you gave (externaljs.js), you would have the script ask the server what $color is, via HTTP. You can also point the script tag at a PHP script that generates the JavaScript you want. It depends on what you need to do.
It helps to have some understanding of taint checking, data verification, and security ;)
As the others are saying, javascript doesn't have access to php variables. However, it does have access to the DOM. So, you can use php to add attributes to some page element. And then you can access those attributes with javascript.
e.g. <div id='apple' class='red'> is completely available to javascript
Don solution is good, furthermore if you want to use a php array in an external javascipt this can help you:
PHP:
<?php
$my_php_array = [];
?>
HTML:
<script type="text/javascript"> var my_js_array = <?php echo json_encode($my_php_array);?> ; </script>
<script src = "../public/js/my-external-js.js"></script>
Javasript: (You can now use the array like a normal Javascript array)
my_js_array[0]
my_js_array.length
externaljs.js is a static file. Of course it can't access PHP data. The only way to pass PHP data to a js file would be to physically alter the file by writing to it in your PHP script, although this is a messy solution at best.
Edit in response to Ólafur Waage's answer: I guess writing to the js file isn't the only way. Passing the js through the PHP interpreter never crossed my mind (for good reason).
<script type="text/javascript" src="externaljs.js"></script>
You could change it to
<script type="text/javascript" src="externaljs.php"></script>
And the PHP script could just write JavaScript like that :
<?php
$fruit = "apple";
echo 'var fruit = '.json_encode($fruit);
...
Though using AJAX like said Sepehr Lajevardi would be much cleaner
2017-2018 and above solution:
Since nobody bringed it up yet and I guess no one thought of combining the functions base64_encode and json_encode yet, you could even send PHP Array variables like that:
index.php
<?php
$string = "hello";
$array = ['hi', 'how', 'are', 'you'];
$array = base64_encode(json_encode($array));
Then you could just load your desired js file with the parameter for a query string like this:
echo '<script type="text/javascript" src="js/main.php?string='.$string.'&array='.$array.'">';
Then js/main.php will look like this for example. You can test your variables this way:
js/main.php
<?php
if ($_GET['string']) {
$a = $_GET['string'];
}
if ($_GET['array']) {
$b = $_GET['array'];
}
$b = json_decode(base64_decode($b));
echo 'alert("String $a: + '.$a.'");';
echo 'alert("First key of Array $array: + '.$b[0].'");';
exit();
?>
The following will then output when you open your index.php. So you see, you don't open js/main.php and you still got the javascript functionality from it.
You can include() them just as you would anything else:
<?php
$fruit = "apple";
$color = "red";
?>
<script type="text/javascript">
<?php include('/path/to/your/externaljs.js'); ?>
</script>
This will basically render the external file as inline js. The main disadvantage here is that you lose the potential performance benefit of browser caching. On the other hand, it's much easier than re-declaring your php variables in javascript.
You cant do that and dont try to as this is not a recommended approach, However you can pass php variables as a function parameters to function written in external js

Categories