Javascript in PHP code - php

I found this code on the internet on how to to display message/pop up box.
<? echo "<script language=\"JavaScript\">\n";
echo "alert('$msg1')";
echo "alert('$msg2')";
</script>";
?>
AND
<? echo "<script>alert('$msg1' )</script>" <?
I want to display messages to the user by popup message. all the messages will be appears in one message box. For above example, the message will be appeared in two box.
Can it be done in all in one box? I try using '\n' or 'br>'...also cannot or i did it wrong? Any idea? Is there any reference or tutorial on this?

<?
echo "<script type=\"text/javascript\">\n";
echo "alert('$msg1" . '\n' . "$msg2');";
echo "</script>";
?>
EDIT: But your users may find alert annoying. Look into DIV-based dialogs.
"alert('$msg1" and "$msg2');" use double quotes to allow for variable interpolation. '\n' is single-quoted so backslash will not be an escape (we want it to be interpreted by JS, not PHP). . is PHP's concatenation operator.

There's a few other issues here.
It is using Javascript alert boxes, which are ugly, and modal. It's bad for users. Modal in the whole-of-browser sense, so (depending on the browser) users can't even go and do something in another tab while this message is on screen; they must dismiss it first. It's much better to place the message in a well styled <div> for example. You could still use some unobtrusive script (like jQuery) to allow users to hide the box if you were so inclined.
Any apostrophes in $msg1 and $msg2 won't be escaped in the Javascript output. This can be a security problem if you're accepting user input as part of these variables. You could use addslashes() to partially fix this, but you'd also need to escape the characters "</" (or "</script" if using HTML) if they might appear, and possibly other variants too.
If you read and accept the above problems and still want to achieve this, here's a safer (though I'm still not sure if it's perfectly safe) alternative:
<?
echo "<script type=\"text/javascript\">";
echo "alert('" . str_replace("</", "<'+'/", addslashes($msg1).'\n'.addslashes($msg2)) . "');";
echo "</script>";
?>

Instead of:
echo "alert('$msg1')";
echo "alert('$msg2')";
Try:
echo "alert('$msg1, $msg2')";

Here is modified example from w3schools.com tutorial if you want to display messages before submit is processed:
<html>
<head>
<script type="text/javascript">
function disp_alert()
{
<?php echo "alert('".$msg1.'\n'.$msg2."');"; ?>
}
</script>
</head>
<body>
<input type="button" onclick="disp_alert()" value="Display alert box" />
</body>
</html>

Related

Issues with calling a JavaScript function from PHP

I have created a form to upload a a newsletter into the database. I'm using the iFrame method to post the date without the page refresh and I'm displaying a nice jQuery dialog for the loading.
I am now having issues with closing that dialog when the upload is complete. All the tutorials I have read online say that I must just echo out the code like this:
<?php
echo "<script type='text/javascript>uploadComplete();</script>";
?>
Now the JavaScript does run when I do something stupid to test like just echo out an alert, but when I try and call any function or just go straight to the jQuery to close the dialog it just says that the function is not defined. I can post my code if it is necessary, but it's pretty standard and I didn't think I would need to in this kind of example.
Any help would be appreciated! Thanks in advance.
you forgot ' in the end of 'text/javascript'
echo "<script type='text/javascript'>uploadComplete();</script>";
NB : the type attribute is entirely unnecessary if the script is JavaScript
using just php
echo '<script type="text/javascript">'
, 'jsfunction();'
, '</script>';
escaping from php mode to direct output mode
<?php
// some php stuff
?>
<script type="text/javascript">
jsFunction();
</script>
I eventually solved this by using the following code:
<?php
echo "<script type='text/javascript>top.uploadComplete();</script>";
?>
The "top" keyword just solved all of my problems. I hope this helps whoever has the same issue I had!

echo javascript from php not working?

So, in an html page I'm trying to have a php segment echo some javascript code, as seen here:
<?php
echo "This was legitimately hit";
if(!empty($_POST['name']))
{
echo '<script type="text/javascript">alert("We got the name");</script>';
}
else
{
echo '<script type="text/javascript">alert("We DID NOT get the name");</script>';
}
?>
and from what I've read online, this seems to be a legitimate way of doing things, but the page seems to be reading the first part up until the first closing chevron (seen just below here) as a comment.
<?php
echo "This was legitimately hit";
if(!empty($_POST['name']))
{
echo '<script type="text/javascript">
Then it reads the else and next echo as plain text, and puts it on the webpage. the next javascript code block then gets read as a regular javascript code block, so the page does a pop-up saying it did not get the name. The closing bracket and closing chevron then just get output as more text.
So in the end the page just ends up having
alert("We got the name")'; } else { echo ''; } ?>
printed on it as plain text, and has a pop-up that says we received no name.
What is going wrong here?
Sounds like the file isn't being processed as PHP. Does the file name end in .php? Are you sure PHP is installed and hooked up correctly to the web server?
edit: To handle the Facebook requests in the same page:
<?php
if (isset($_POST['facebook_request_field'])) {
// handle the Facebook request, output any necessary response
// then exit
exit;
}
?>
<!-- display the web page normally here -->
So for your test page:
<?php
if (isset($_POST['name'])) {
echo '<script type="text/javascript">alert("got a name!");</script>';
exit;
}
?>
<script type="text/javascript">alert("No name.");</script>
(That's actually identical in function to what you already have, so maybe I'm misunderstanding the purpose.)
Between We got the signed request and We got the name, I think you haven't given us the actual code that's causing the error. Double check that, and make sure you don't have any stray single quotes before your alert call.
There are missing ; after the alert. Have you tried correcting this first?

popup window not work in php echo

it can appear a simple question but i have searched untill writing here but no answer. i have a php code and i what to start a pop up window after echo :
echo "<A HREF='map2.php' onClick='return popup(this,'notes')'>WHATEVER</A>";
in the head section i have :
<SCRIPT TYPE="text/javascript">
<!--
function popup(mylink, windowname)
{
if (! window.focus)return true;
var href;
if (typeof(mylink) == 'string')
href=mylink;
else
href=mylink.href;
window.open(href, windowname, 'width=400,height=235,scrollbars=yes');
return false;
}
at the end is the ending script tag but i dont succide in adding it.
anyway.the pop up doesn work. the link opens in the same page.
i also tried :
About
and it doesnt work. it opens in the same page. The funny thing is that all these 2 solutions worked in html page, but when used between php , after "echo" , it doesnt work anymore.
In the first line you posted (the php echo), it seems to me you have a problem with ' in side '
Try the following:
echo "WHATEVER";
The issue here your quoting.
When outputting HTML I recommend using single quotes with echo as it allows you to use the proper double quotes for the HTML tags.
echo 'Whatever';
The problem with your original code was that you had quotes within quotes that were breaking the syntax. Read the link I posted to see how to handle quotes properly with PHP.

including php in html code within php

<?php
if(isset($left))
{
echo "<button name = rightname onclick= \" disp();\">". "$left"."</button>";
}
?>
here disp is a php function. but i am not able to use it. can anybody say me how to overcome this problem...
The only way to run a PHP function in response to a user clicking on something in their browser, is to send an HTTP request to the server.
The simplest way to achieve this would be:
<?php echo htmlspecialchars($left); ?>
You then need to write disp.php such that it includes the function you want to run, and calls it. Then you need to return an appropriate response to the browser (e.g. a page to display or a redirect (via Location) header.
You could also look at using XMLHttpRequest (probably via a third party library such as YUI or jQuery) to make the HTTP request using JavaScript without the user leaving the page (Ajax). Given the amount of knowledge you appear to have based on your question, you might need an introduction to JavaScript first.
Simply try like this
<?php
if(isset($left))
{
?>
<button name ="rightname" onclick= "<?php disp();?>"><?php echo $left;?></button>
<?php
}
?>
onclick only works for javascript functions not PHP functions, that won't work.
See BoltClock's comment under your question.
One of the ways to run php in combination with javascript is using an ajax post (http://api.jquery.com/jQuery.post/). Eg:
$.post("test.php", { name: "John", time: "2pm" },
function(data){
alert("Data Loaded: " + data);
});
And when concatenating variables with string you don't need to put the variable between double quotes, or just put the variable in the string without closing the double quotes.
echo "<button name='rightname' >". $left."</button>";
Or (will only work when using double quotes)
echo "<button name='rightname' >$left</button>";
if you don't use Aston's answer, you can correct your code as follow:
<?php
if(isset($left))
{
echo '<button name ="rightname" onclick= "' . disp() . '">'. $left .'</button>';
}
?>
I wanted to point that you can use single quotes to make it easier to handle double-quotes inside.
Before bothering with AJAX, would you mind me asking what the disp() function does? If it's something that doesn't heavily rely on server interaction (file operations, db connections), we may be able to help you port it to JS and remove the need for AJAX.
I would write this:
<?php if(isset($left)) : ?>
<button name="rightname" onclick="<?php disp(); ?>"><?php echo $left ?></button>
<?php endif; ?>

Echo PHP variable from JavaScript?

I have a PHP page with some JavaScript code also, but this JavaScript code below doesn't seem to work, or maybe I'm way off!
I am trying something like this:
var areaOption=document.getElementById("<?php echo #$_POST['annonsera_name']?>");
areaOption.selected=true;
Also I have tried this, but it only alerts a BLANK alert-box:
alert (<?php echo $test;?>); // I have tried this with quotes, double-quotes, etc... no luck
Am I thinking completely wrong here?
UPDATE
Some PHP code:
<?php
$test = "Hello World!";
?>
In your second example, you are missing quotes around the string (so H is interpreted as a variable - which you didn't set).
Test this:
alert (<?php echo "'H'";?>);
OR
alert ('<?php echo "H";?>');
PHP runs on the server side and Javascript is running on the client side.
The process is that PHP generates the Javascript that will be executed on the client side.
You should be able to check the JS that is generated just looking at the code. Of course, if the JS relies on some PHP variables, they need to be instanciated before the JS is output.
<?php
$test = 'Hello world';
?>
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
will work but
<html>
<body>
<script>
alert('<?php echo $test; ?>');
</script>
</body>
</html>
<?php
$test = 'Hello world';
?>
will not
Use json_encode to convert some text (or any other datatype) to a JavaScript literal. Don't just put quotes around the echoed string — what if the string has a quote in it, or a newline, or backslash? Best case your code fails, worst case you've got a big old cross-site-scripting security hole.
So,
<?php
function js($o) {
echo json_encode($o, JSON_HEX_TAG|JSON_HEX_APOS|JSON_HEX_QUOT|JSON_HEX_AMP);
}
?>
<script type="text/javascript">
var areaOption= document.getElementById(<?php js($_POST['annonsera_name']); ?>);
areaOption.selected= true;
alert (<?php js('Hello World'); ?>);
</script>
Your using #$_POST indicates that you have received (or are expecting) errors - check your generated source to see if the value was output correctly. Otherwise document.getElementById will fail and you'd get no output.
alert("Delete entry <? echo $row['id']; ?> ")
If your extension is js, php will not work in that file.
The reason being, php parses on files that it is supposed to. The file types that php will parse are configured in httpd.conf using AddType commands (or directives, whatever they are called).
So you have 3 options:
add filetype js to the list of files php will parse (BAD, VERY BAD)
make the script inline to some php file
rename the file to script.js.php, and at the beginning of the file, specify the content type, like so:
<?php header( 'content-type: text/javascript' ); ?>
Cheers!

Categories