This question already has answers here:
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 1 year ago.
I'm writing mostly in PHP, but one function requires me to use JavaScript. I need to access a PHP variable in my JavaScript. I've placed the following code between the <head> tags:
<script>
$(document).ready(function(){
$(document).keyup(function(e) {
if ($('.pho_big').is(':visible') && e.keyCode==27) {
var js_link = '<?php echo $p_link; ?>';
window.location.href = js_link;
}
});
});
</script>
In short, when the esc key is pressed, I want to go to $p_link. So I'm trying to copy $p_link to js_link and go there. Instead of getting the contents of $p_link, my browser is trying to go to <?php%20echo($p_link)%20?>, which is obviously incorrect.
I've already gone here, here, and here, all of which seem to tell me to do exactly what I'm doing. My knowledge of JavaScript is near zero, so I'm probably missing something simple, but I don't know enough to know what or troubleshoot.
it looks like <?php echo $p_link; ?> is not interpreted by php.so js_link contains string <?php echo $p_link; ?>.when you set window.location.href to <?php echo $p_link; ?> . browser tries to go to [less_than]?php%20echo($p_link)%20?[greater_than] which is url encoding of <?php echo $p_link; ?>.
(sorry,since I have low reputation, I cant post comment)
Related
This question already has answers here:
Pass a PHP string to a JavaScript variable (and escape newlines) [duplicate]
(14 answers)
Closed 5 years ago.
I'm trying to concatenate a link in a javascript function with a php variable. But whatever a try to write after ""+ doesn't get displayed and the whole program stops working. The variable is defined in a different page. I tried REQUEST to access to it, but it's not working.
function popupEvent(){
$('#btnClose').unbind("click");
$('#btnClose').click(function(){
window.location = SITEURL+"cart/rollPdf/?POrderNo="+implode(',', $orderIDArr);
window.open(ord,'winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');
return false
});
}
Whenever you want to use PHP variable into JS, you need echo it. Ex, <?php echo implode(',', $orderIDArr);?>
In your code try Like this,
function popupEvent(){
$('#btnClose').unbind("click");
$('#btnClose').click(function(){
window.location = SITEURL+"cart/rollPdf/?POrderNo=<?php echo implode(',', $orderIDArr);?>"; // Changed here
window.open(ord,'winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');
return false
});
}
Hope this will help you to solve your problem...
EDIT:
function popupEvent(){
$('#btnClose').unbind("click");
$('#btnClose').click(function(){
ord = SITEURL+"cart/rollPdf/?POrderNo=<?php echo implode(',', $orderIDArr);?>"; // Changed here
window.open(ord,'winname','directories=no,titlebar=no,toolbar=no,location=no,status=no,menubar=no,scrollbars=no,resizable=no,width=400,height=350');
return false
});
}
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 is similar to PHP generated content inside Javascript breaking script, however I'm not able to understand where I'm wrong.
Here is the brief. I'm trying to output 10 strings from MySQL DB into a javascript array s, (s[1] to s[10]) (stored in one MySQL table under columns pt1 to pt1 - info so code is understandable to all). (Note $apos is just the apostrophe string - not a concern here).
<?php
echo "<script>\n";
echo "var s = [];\n";
for($i=1;$i<=10;$i++) {
echo "s[".$i."] = ".$apos.$r['pt'.$i].$apos.";\n";
}
echo "</script>";
?>
It produces the right code when I look at the source by 'View Source' in browser:
<script>
var s = [];
s[1] = 'a';
s[2] = 'b';
.
.
s[10] = 'j';
</script>
However, this doesn't work as a script (meaning if I check in Google developer tools, and I click on content inside the 'script' tag elements, it is told to be 'text', and not 'script' in the bar below).
However if I remove the PHP, and manually write the whole script the same way, it works just fine. I have tried removing the \n linebreaks in the PHP code, but still the same problem.
Something in PHP is breaking the script. Can you help?
My best guess is that one (or more) of your strings contains a character (such as the apostrophe) which breaks the PHP output. Still the best solution was already prosposed by Passery in your comments section:
echo '<script>';
echo 'var s = ' . json_encode($info);
echo '</script>';
I think you may have been misreading the developer tools. When I look closely at Chrome, it does indeed identify your script as text, possibly because the default type is text/javascript. Putting an explicit type declaration on the <script> tag made no change.
However, when I add echo "alert('s[1]='+s[1]);"; after the for loop, the alert displays, and I am able to see the values of the other s[i] with the debugger.
In other words, I think your generated JavaScript worked all along.
I know you've already fixed the problem another way. I post this answer only in case it may help others.
Here is what I used for testing:
<?php
$a = "-abcdefghij";
$apos="'";
echo "<script type=\"text/javascript\">";
echo "var s = [];";
for($i=1;$i<=10;$i++) {
echo "s[".$i."] = ".$apos.$a[$i].$apos.";\n";
}
echo "alert('s[1]='+s[1]);";
echo "</script>";
?>
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;