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 js function that make some ajax post and a php handler that parse the $_POST and do something. I would use in js and php the same constants. For example if i put some define in php:
define('done','1',TRUE);
I would like to have it on js too. Are there some way to have some constants declared one time and usable in all this 2 languages?
Define your constants in PHP but output them to your javascript by either writing them to an index.php master file (or similar) or fetch them by ajax
Use get_defined_constants to retrieve all constants and parse that to json
ie (I am without environment at the moment and unable to test this)
<script type="text/javascript">
var constants = <?php echo json_encode(get_defined_constants()); ?>
</script>
Have a look at the documentation on get_defined_constants how to retrieve your personal constants, http://php.net/manual/en/function.get-defined-constants.php
You could write your js in a PHP file and use your function returns echo'd out in your javascript i.e.
<?php
$someid = 'wrapper';
?>
<script type="text/javascript">
document.getElementById("<?php echo $someid; ?>");
</script>
Related
This question already has answers here:
Retrieving JSON array in Javascript from PHP
(3 answers)
Closed 6 years ago.
I have a JSON object array that is created in PHP that I need to be able to send down to javascript so that javascript can sort through the JSON using JSON.parse
What is the best way to go about doing this?
Assuming you have this endpoint that produces that JSON data : sample.com/json.php
In your json.php
<?php
echo json_encode($your_json_variable);
?>
And in your script, using Jquery AJAX :
$.getJSON('sample.com/json.php', function(data){
$.each(data, function(k,v){
console.log(v);
});
});
It actually depends on how you want to get it with javascript. If you will get it with ajax you can use it like below to write it out.
<%php echo json_encode($your_json_data);%>
If your javascript is on same file as your json array is than
<script language="javascript">
var myJSJson = <%php echo json_encode($json_data)%>;
</script>
Would do the trick.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 6 years ago.
I am developing a web application in php, and I've used javascript many times. Now I need to use a php variable in javascript.
For example, a variable generated from a SQL query return, or a session variable, which are needed in the javascript section.
What is the best way to use a php variable in javascript?
Maybe you could do something like:
<script>
var a = <?php echo $a; ?>; //for numbers
</script>
That's one basic way of accomplishing what you want.
EDIT: As JiteshNK also pointed out, you could also do:
<script>
var a = <?php echo json_encode($a); ?>; //safest solution
</script>
You can do something like this :
If a normal variable:
<script type= "text/javascript">
var a = <?php echo $var; ?>;
</script>
OR
If you have json :
<script type= "text/javascript">
var a = <?php echo $json_encode($var); ?>;
</script>
If its simple string variable then use.
<script>
var a = "<?php echo $var; ?>";
</script>
If php variable is array then
var resultArray = <?php echo json_encode($varArr); ?>
// Use resultArray values in javascript
$.each(resultArray, function(index, value) {
}
I don't fully understand what you are trying to do.
Basically, I don't thing what you would like to do is possible.
Reason: JavaScript is running in the browser. At the time when your JavaScript code is executed, the page has already been loaded. At that time, there is no such thing as PHP available anymore. Your browser only knows about HTML.
PHP is running on the server and is used to "construct" or "build" or "compile" your HTML page.
What you definitely can do is: You can use PHP to create your JS code dynamically (like you already do that with your HTML file) and there use PHP to populate a JS variable with the contents of a PHP variable.
This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
PHP code is not being executed, but the code shows in the browser source code
(35 answers)
Closed 4 months ago.
I have a PHP file that creates a randomized string stored in a variable. I want to access this variable with JavaScript but the methods I've found online doesn't seem to be working. This is the code I have so far:
var test = "<?php echo json_encode($myVariable); ?>";
alert(test);
$myVariable is just a string: "testing".
I thought "testing" would be alerted but instead the code itself is (<?php echo json_encode($myVariable); ?>). When I take away the quotations, nothing happens. I'm very new to JavaScript so I'm not sure what's wrong. Is there another way I can access a PHP variable with JavaScript?
you can transfer variable contents by this
var test = "<?php echo $myVariable; ?>";
alert(test);
There are few way of accessing variables from php with javascript AJAX/Cookies/_SESSION or echo directly to javascript.
AJAX
Is more readable with better separations between layers it also allows for async transfer. BUT it can be very slow adding HTTPrequest can lead the website to slow down alot if there is alot of variable to request from php.
Cookies
I dont recommend it as there will be alot of necessary data store on the client side.
_SESSION
I recommend you using _SESSION as new developer will find it easier to use. it works similar to cookies but the only difference is once the page is closed the data is erase.
Echo directly to javascript
Easy to implement but horrible code practise.
All the above answers I explain quite vague do your research on topics, look for _SESSION to start with then move on to AJAX if appropriate.
Code example
PHP
if you are getting data from mysql
$_SESSION["AnyVariable"] = my_sql_query ("SELECT someData FROM someTable")
Or if its just a variable in PHP
$SESSION["aVariable"] = whateverValue;
JavaScript
<script type="text/javascript">
function someFunction()
{
var someVariable = '<%= Session["phpVariableSessionName"] %>';
alert(someVariable);
}
</script>
json_encode produces output ready for javascript, you must not put it into quotes:
var test = <?php echo json_encode($myVariable); ?>;
Try it the other way around ...
<?php echo "var test = '" . json_encode($myVariable) . "';"; ?>
This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 8 years ago.
I am trying to use a php variable in my javascript code, but i cant seem to get it working. Here is my js and php code:
<?php $s = "woo"; ?>
var images = <?=$s?>;
What i want to achieve, is a php variable in javascript ENCLOSED with ['']; With other words, so that the javascript code reads it like this: ['woo'];
I could really need some help, as i am very new to javascript. Thanks in advance.
I recommend using json_encode for all values "passed" to JavaScript - this will prevent against injection, accidental or otherwise. It also trivially handles quotes and allows complex object graphs to be supplied. If not already, I imagine that images is really, or should be, an array ..
var images = <?= json_encode($s) ?>;
Or
var images = <?php echo json_encode($s); php?>;
Look at the actual HTML to see what is being emitted, and that it is valid - the original yields JavaScript akin to var images = woo;, which will result in a ReferenceError (on woo).
One trick you can use is this, when you are inside a .js file it can be helpful, because php doesnt work.
Put the value of your php value inside a div as content, and then grab that in the javascript.
in the php file:
<div id="sVar" style="display:none;"><?php echo $s; ?></div>
in js:
var images = document.getElementById('sVar').innerHTML;
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 a Javascript variable as "name" I want to add that to my php code. The php code uses the JS variable for a select statement. This is what I am Trying, but I am getting a syntax error;
<script type="text/javascript">
function fillform(name){
<?php $name = "SELECT * FROM table_name WHERE name = ". ?> name <?php ." "; ?>
console.log(<?php echo $name; ?>);
}
</script>
PHP code is executed by the server.
Then the server sends the output of that code to the client in html form..
Javascript is executed by the client so you cannot combine them.
A solution could be the use of AJAX which allows javascript to call a php file and get the output of the executed code..