Echo PHP code inside Javascript - javascript

I am having problem getting this to work. I am trying to echo some php code to html if the page is in an iframe. Below is a short example of the php code i try to echo (the real code i try to echo is much longer)...
<?php $pic='https://cdn.pixabay.com/photo/2015/06/19/17/58/sample-815141_960_720.jpg'; ?>
<div id="frameid"></div>
<script type="text/javascript">
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
if (inIframe()) {
var node = document.getElementById('frameid');
node.innerHTML('<?php echo '<img width="100%" src="'.$pic.'"></img>'; ?>');
}
</script>

Seems there was some quotes issue. You can try the below code:
<div id="frameid"></div>
<script type="text/javascript">
function inIframe () {
try {
return window.self !== window.top;
} catch (e) {
return true;
}
}
if (inIframe()) {
var node = document.getElementById('frameid');
node.innerHTML(<?php echo "...something involving html and php variables...."; ?>);
}
</script>

Can you try this?
var pic = ;
innerHTML("");
I think is more clear to separate js from php, and recomanded

You are having troubles with single quote, you may consider this function (taken from WP https://developer.wordpress.org/reference/functions/_wp_specialchars/) to escape quote (single and double)
node.innerHTML('<?php echo esc_attr('<img width="100%" src="'.$pic.'"></img>'); ?>');
where you can define
function esc_attr( $text ) {
return _wp_specialchars( $safe_text, ENT_QUOTES );
}

Related

Calling javascript function in my PHP code

I searched up some questions on stackoverflow and used the suggested solutions, however, I can't seem to get my php code working the way I'd like.
When I visit projects.php?message=success or projects.php?message=removed, the JavaScript function does not execute. In my debugging, I've confirmed the JavaScript is working correctly by attaching it to a button with the onclick property.
My php code:
<?php
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$alert= GET('message');
if ($alert == success) {
echo '<script type="text/javascript"> window.onload=success(); </script>';
} elseif ($alert == removed) {
echo '<script type="text/javascript"> window.onload=removed(); </script>';
}
?>
My JavaScript code:
<script>
function success() {
$.notify({
// options
icon: "pe-7s-cloud-upload",
message: 'New project entry was successfully added.'
},{
// settings
type: 'success'
});
}
function removed() {
$.notify({
// options
icon: "pe-7s-trash",
message: 'Project entry was successfully deleted.'
},{
// settings
type: 'danger'
});
}
</script>
You need quotes around the texts and properly set window.onload:
<?php
function GET($key) {
return isset($_GET[$key]) ? $_GET[$key] : null;
}
$alert = GET('message');
echo "<script>window.onload = function () { ";
if ($alert == "success") echo "success();";
else if ($alert == "removed") echo "remove();";
echo " };</script>";
?>
If those two are all you need, you can also do this:
$alert = GET('message');
if ($alert == "success" || $alert == "remove") {
echo "<script>window.onload = $alert;</script>";
}
Edit:
To clarify an issue from the comments: to set window.onload to a function, one cannot use
window.onload = myFunc(); // WRONG!
(This will call the function, then set window.onload to the result)
The correct way is:
window.onload = myFunc;
// OR
window.onload = function () {
myFunc();
};
I've tested is the inexistent constant you're using called success.
As #Chris G said
Change the if for :
if ($alert == "success")

How to trigger js function inside php?

if (!$errors) {
//Call Js function without any events
}
I want to call js function once inside if came,How to call js function inside if condition?Is it possible to call js fucntion without any events inside php tag?
with jquery
if (!$errors) {
echo "<script type='text/javascript'>
$(document).ready(function(){
myfunction();
});
</script>";
}
without jquery and wait unlit whole page is loaded
if (!$errors) {
echo "<script type='text/javascript'>
window.onload = function() {
myfunction();
};
</script>";
}
and without Onload
if (!$errors) {
echo "<script type='text/javascript'>myfunction();</script>";
}
You can also use this way :
<?php
// php code
if(condition){
?>
<script type="text/javascript">
jsFunction();
</script>
<?php
}
// php code
?>
You can also use jquery:
if (!$errors) {
echo "<script type='text/javascript'>
$(document).ready(function(){
myfunction();
});
</script>";
}
You could just make an echo and call it between two script tags.
Like :
if (!$errors) {
echo "<script> myfunction(); </script>";
}

How to use php-function-output as input for javascript?

I have a php-function trans to translate text. How to input trans-output in javascript?
<script>
function fregister_submit(f) {
if (!f.agree.checked) {
alert("<?=trans('회원가입약관의 내용에 동의하셔야 회원가입 하실 수 있습니다.')?>");
f.agree.focus();
return false;
}
if (!f.agree2.checked) {
alert("개인정보처리방침안내의 내용에 동의하셔야 회원가입 하실 수 있습니다.");
f.agree2.focus();
return false;
}
return true;
}
Try this:
alert("<? echo trans('회원가입약관의 내용에 동의하셔야 회원가입 하실 수 있습니다.'); ?>");
Converting php variables to be readable for javascript can be done like this:
<?php echo json_encode($var); ?>;
Everything else a simple echo does the job

PHP isset variable than jquery and javascript should work

I want to know if my php variable does not exists, then I want to execute my javascript.
For example-
<?php
if(!isset($_REQUEST['myVar'])){
?>
<script>
alert('variable not exist');
</script>
<?php
}
?>
Is this right way to use javascript code in php extension file
I know all other answers solve your issue but i prefer it to do this way
<script>
<?php
$isset = !isset($_POST['myVar']) ? 'true' : 'false';
echo "var isset = $isset;";
?>
if(isset) {
alert('variable not exist');
}
</script>
when php render your page it will give this output
<script>
var isset = true;
if(isset) {
alert('variable not exist');
}
</script>
Do it like this and it will work:
if (!isset($_REQUEST['myVar'])) {
echo "<script>alert('variable not exist');</script>";
}
you can try writing this piece of code where you want the script to be placed:
<?php
if (!isset($_REQUEST['myVar'])) {
echo '<script>
alert("variable not exist");
</script>';
}
?>

$_REQUEST['id'] from page inside a php file called by a javascript to another php page

I'm trying to get the value 3 from this link: index.php?subtopic=example&id=3
Normally I would use the $_REQUEST['id'] but I'm facing another situation here.
I got the example1.php:
<script type="text/javascript" src="js/chatbox.js"></script>
...
<div id="chat_box"></div>
And then the chatbox.js:
setInterval( function() {
$('#chat_box').load('chatbox.php');
} , 100 );
And finally the chatbox.php:
echo $_REQUEST['id'];
but I can't get the id value here :/ Please Help!!!
Basically you want to parse the id out of the URL and send it to the chat - let's do this:
<script type="text/javascript">
function getID() {
var tmp=location.href.split('?');
if (tmp.length!=2) return -2;
tmp=tmp[1].split('&');
for (i=0;i<tmp.length;i++) {
var param=tmp[i].split('=');
if (param.length!=2) continue;
if (param[0]!="id") continue;
return parseInt(param[1]);
}
return -3;
}
var chaturl='chatbox.php?id='+getID();
</script>
<script type="text/javascript" src="js/chatbox.js"></script>
...
<div id="chat_box"></div>
...
setInterval( function() {
$('#chat_box').load(chaturl);
} , 100 );
I solved it here:
example1.php
echo "<script type='text/javascript'>
setInterval( function() {
$('#chat_box').load('chatbox.php?id=".$_GET['id']."');
} , 100 );
</script>";
echo '<div id="chat_box"></div>';
and chatbox.php:
echo $_GET['id'];

Categories