How can we use PHP code in JavaScript?
Like
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
Please suggest a better way.
If your whole JavaScript code gets processed by PHP, then you can do it just like that.
If you have individual .js files, and you don't want PHP to process them (for example, for caching reasons), then you can just pass variables around in JavaScript.
For example, in your index.php (or wherever you specify your layout), you'd do something like this:
<script type="text/javascript">
var my_var = <?php echo json_encode($my_var); ?>;
</script>
You could then use my_var in your JavaScript files.
This method also lets you pass other than just simple integer values, as json_encode() also deals with arrays, strings, etc. correctly, serialising them into a format that JavaScript can use.
If you put your JavaScript code in the PHP file, you can, but not otherwise. For example:
page.php (this will work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>;
alert(i);
}
page.js (this won't work)
function jst()
{
var i = 0;
i = <?php echo 35; ?>
alert(i);
}
PHP has to be parsed on the server. JavaScript is working in the client's browser.
Having PHP code in a .js file will not work, except you can tell the server to parse the file you want to have as .js before it sends it to the client. And telling the server is the easiest thing in the world: just add .php at the end of the filename.
So, you could name it javascript.php. Or, so you know what this file is PRIMARILY, you could name it javascript.js.php - the server will recognize it as .php and parse it.
This is the bit of code you need at the top of your JavaScript file:
<?php
header('Content-Type: text/javascript; charset=UTF-8');
?>
(function() {
alert("hello world");
}) ();
Yes, you can, provided your JavaScript code is embedded into a PHP file.
You're pretty much on the ball. The only difference is I'd separate out the JavaScript code so the majority was in an external static file. Then you just define variables or call a function from the actual PHP page:
<script type="text/javascript>
function_in_other_file(<?php echo my_php_var; ?>);
</script>
A small demo may help you:
In abc.php file:
<script type="text/javascript">
$('<?php echo '#'.$selectCategory_row['subID']?>').on('switchChange.bootstrapSwitch', function(event, state) {
postState(state,'<?php echo $selectCategory_row['subID']?>');
});
</script>
Here is an example:
html_code +="<td>" +
"<select name='[row"+count+"]' data-placeholder='Choose One...' class='chosen-select form-control' tabindex='2'>"+
"<option selected='selected' disabled='disabled' value=''>Select Exam Name</option>"+
"<?php foreach($NM_EXAM as $ky=>$row) {
echo '<option value='."$row->EXAM_ID". '>' . $row->EXAM_NAME . '</option>';
} ?>"+
"</select>"+
"</td>";
Or
echo '<option value=\"'.$row->EXAM_ID. '\">' . $row->EXAM_NAME . '</option>';
We can't use "PHP in between JavaScript", because PHP runs on the server and JavaScript - on the client.
However we can generate JavaScript code as well as HTML, using all PHP features, including the escaping from HTML one.
Related
Section 1
I'm trying to return an Array from PHP (after having created the file using fwrite)
I include that file on my next .load method (inside a Div) the new PHP file contains an include 'somefile.php'; there is my array ... and I would simply try to collect from PHP and use it the array with JS....
I once saw something like this ...
$(function(){
alert('<?php for_each($array as $key => $value){
echo $value; // Just an example
}
?>')
});
I wrote this piece of code on the fly so there might be a few sytax errors;
This works fine using PHP inside JS ...
I'm not sure if I heard PHP loads first and then JS ? or was it the other way around ?
Section 2
How about using JS inside PHP ?
for example ....
<?php
echo "var myArray = New Array();"
echo "myArray = ('Apple','Banana','Orange','Kiwis');"
echo "return myArray";
?>
and then being able to fetch the data strait with JS ?
<script type="text/javascript">
for(i=0;i<myArray.length;i++){
alert(myArray[i]);
</script>
So how easy can I manipulate both languages in regards to RETURNING the array for example so it could be used in the global scope?
PHP runs first, so you can use it to write JavaScript code, that will get run once the page has been processed by the browser.
This would build JavaScript code with an array from PHP:
<script>
var myArray = <?php echo json_encode(array('apple', 'orange', 'kiwi'); ?>;
myArray.forEach(alert)
</script>
The other way around, passing data from JavaScript to PHP, can only be accomplished with some form of AJAX.
using PHP in JS : In short, you can echo the values in JS codes, e.g.
window.location = '<?php echo $url; ?>';
using JS in PHP : You can use AJAX . post the values to a PHP script
The PHP runs on the server, so from Javascript's point-of-view (running in the client's browser) it's like the PHP was never even there.
You can easily pass the PHP array to Javascript using PHP's json_encode() function:
$yourPHPArray = array("blah","blah","blah");
echo "var theArray=" . json_encode($yourPHPArray) . ";";
echo "for(var i=0;i<theArray.length;i++)";
echo "{";
echo " window.alert(theArray[i]);";
echo "}";
Is there anyway I can use a php variable in the JQuery script?
Example:
PHP variable: $sr2
Excerpt of JQuery script (with variable): $('#a2_bottom_$sr2')
How can I make it so the variable is valid in that JQuery part?
Thanks
PHP runs on the server, jquery runs on the client. If you want a PHP variable to be available to jquery (and by extension, the underlying javascript engine), you'll have to either send the variable's value over at the time you output the page on the server, e.g.
<script type="text/javascript">
var my_php_var = <?php echo json_encode($the_php_var) ?>;
</script>
or retrieve the value via an AJAX call, which means you're basically creating a webservice.
What you could simply do is use your PHP to echo out the code to initiate a JavaScript variable.
<script type="text/javascript">
<?php
$phpVar = "foo";
echo "var phpVariable = '{$phpVar}';";
?>
</script>
Once the PHP code is parsed, and the HTML is sent to the user - all they will see is the result of the PHP echo -
<script type="text/javascript">
var phpVariable = 'foo';
</script>
Now your phpVariable is available to your JavaScript! So you use it like you would in any other case -
$("div."+phpVariable);
That will retrieve us any <div> element with a foo class -
<div class="foo"></div>
Assuming your jQuery is in the same file:
... $('#a2_bottom_<?php echo $sr2 ?>') ...
You could output it as part of the page in a script tag... i.e.
<script type="text/javascript">
<?php
echo "var sr2 = \"" . $sr2 . "\"";
?>
</script>
Then your jQuery line would be able to access it:
$('#a2_bottom_' + sr2)
how can use JS variable in PHP like this ?
<script>
x = document.getElementById(1).value;
var listOf = <?php echo $listOf[x]; ?>;
</script>
this doesn't work :(
And rightfully so. PHP is executed on the server, while JavaScript is executed in the client's browser. Those are two different contexts and the variables from one are not visible in the second.
You need to have your PHP script output a JavaScript version of the array and then use this one in your script. Something like this:
<?php
echo "listArray = new Array();\n";
foreach ($listArray as $key => $value) {
echo 'listArray[', $key, '] = ', $value, ";\n";
}
You can't use it directly like this.
You'll have to use AJAX to send the value from client side to server side and only then PHP can see it.
Using jQuery it can become really simple though:
x = document.getElementById(1).value;
$.get("mypage.php?x=" + x, function(result) {
alert("response from PHP: " + result);
});
And in the PHP read the x from querystring and send proper output.
it is not possible because both are different languages so you cant use javascript varible
in php inside javascript
This is not possible. PHP is executed serverside, even before its output reaches your browser. JS is executed clientside, in the browser. You can't do this, unless you call some other PHP script with this variable x.
You can't. JavaScript is run in your browser while PHP gets run on the server. The only way for JavaScript to communicate with PHP is by using AJAX (XMLHttpRequest), separating the JavaScript from the PHP.
like this
if you put php in any single or double quotes than it work
<script type='text/javascript'>
x = document.getElementById(1).value;
var listOf = "<?php echo $listOf[x]; ?>";
</script>
This will convert javascript variable to php variable.
<script>
function sud(){
javavar=document.getElementById("text").value;
document.getElementById("rslt").innerHTML="<?php
$phpvar='"+javavar+"';
echo $phpvar.$phpvar;?>";
}
function sud2(){
document.getElementById("rslt2").innerHTML="<?php
echo $phpvar;?>";
}
</script>
<body>
<div id="rslt">
</div>
<div id="rslt2">
</div>
<input type="text" id="text" />
<button onClick="sud()" >Convert</button>
<button onClick="sud2()">Once Again</button>
</body>
Demo: http://ibence.com/new.php
I want to dynamically tell a javascript which <div> to hide, but I dont know how to send the request to the javascript as it is a client side script.
for eg:
<?
$divtohide = "adiv";
?>
<script language="javascript">
function hidediv($divtohide) {
................
}
</script>
Assuming $divtohide actually contains the ID of a <div> element and not a JavaScript variable name, write your JavaScript function as normal:
function hidediv(divtohide) {
// Your code may differ here, mine's just for example
document.getElementById(divtohide).style.display = 'none';
}
And print out the PHP variable only when you're calling it, within a pair of quotes:
hidediv("<?php echo addslashes($divtohide); ?>");
addslashes() ensures that quotes " in the variable are escaped so your JavaScript doesn't break.
as BoltClock wrote, use php to pass the variable.
but you can do it by most simple way, just write hidediv("<?=$divtohide?>")
<script type="text/javascript">
function hidediv() {
divobj = document.getElementById('<?= $divtohide ?>');
divobj.style.display = 'none';
}
</script>
I want to do some innerHTML replacements, but using PHP includes, I dont get how. I have done innerHTML replacements before, just not with PHP.
I have:
var xmlHttp
function DisplayAerialProductListing()
{
var strStartCode="<p></p>";
document.getElementById("txtData").innerHTML= strStartCode;
var code="";
code = code + "<?php include 'newpage.inc'; ?>";
document.getElementById("txtData").innerHTML= code;
}
I have the 'txtData' Div as:
initially and I want to replace with code from the .inc I mention. I use .inc to separate out pieces of the site and to make like easier for the designer so they dont go breaking stuff!
In the .inc I just have HELLO for now.
It doesn't work. What is the trick?
PHP is processed server-side; Javascript is processed client-side. You can't insert PHP code via Javascript because you've already left the server. Normally what you'd do is use AJAX to run the PHP code on the server and then insert the results dynamically into the page.
Using jQuery, you can nail that almost effortlessly:
<p id="myParagraph"></p>
<script>
//when the DOM is ready
$(document).ready(function() {
//replace contents of p id="myParagraph" with output of specified script
$('#myParagraph').load('myPage.php');
});
</script>
Still, make sure you understand the difference between client and server as per #Dav's answer.
See http://docs.jquery.com/Ajax
<script style="text/javascript" language="javascript">
<!--
function check_country()
{
var sel_country = document.getElementById("country");
if(sel_country.value == "US")
{
<?php
$query = "SELECT stateName, stateAbbrev
FROM states
WHERE stateEnabled = '1'
ORDER BY stateName ASC";
$result = mysql_query($query);
$prov = "<select name=\"state\" id=\"state\" class=\"widthed\">";
while($row = mysql_fetch_row($result))
{
$prov .= "<option value=\"$row[1]\">$row[0]</option>";
}
$prov .= "</select>";
?>
document.getElementById("tab1").rows[2].cells[3].innerHTML = "*State:";
document.getElementById("tab1").rows[3].cells[0].innerHTML = "*Zip Code:";
document.getElementById("tab1").rows[2].cells[4].innerHTML = <?php echo $prov; ?>;
}
}
-->
</script>
That will work as long as your JavaScript file is parsed by PHP, ie. with an .htaccess that says SetHandler application/x-httpd-php .js. You'll want to escape the text inside the include, so it may be better to use PHP's file_get_contents() and addslashes(). Here's an example of how to super sanitize a string in PHP that is destined for JavaScript: http://sixohthree.com/241/escaping
An alternate solution would be to load the page content via XMLHttpRequest.