I have my Javascript inside echo, but i want it to have a php also inside. I dont know if it is possible, just want to know the right way. cheers.
<?php
if($_GET["main"]=="add-doc"){
echo "<script>
var r=confirm(\"Press a button\");
if (r==true)
{
<? require_once(\"doc_add.php\"); ?> <--- PHP here
}
else
{
x=\"You pressed Cancel!\";
}
</script>";
}
?>
-
php can output javascript without problem. just not sure what you want to accomplishPetros Mastrantonas– Petros Mastrantonas2013年06月06日 07:35:58 +00:00Commented Jun 6, 2013 at 7:35
-
possible duplicate of Reference: Why does the PHP code in my Javascript not work?PleaseStand– PleaseStand2013年06月06日 07:37:26 +00:00Commented Jun 6, 2013 at 7:37
-
@PetrosMastrantonas - i want to confirm the user before going to certain page, if it answer yes i want to require the page. any other way or suggestions i could try?Ikong– Ikong2013年06月06日 08:02:50 +00:00Commented Jun 6, 2013 at 8:02
4 Answers 4
Technically is there no difference including PHP in HTML or in CSS or in JavaScript. HTML is static. CSS and JavaScript are client side dynamic languages to complement HTML. They add to HTML what PHP or any other server side language can not do server side.
That is why using PHP in JavaScript is considered an anti-pattern. CSS and JavaScript should perform actions that the server side is not able to control. All the information for those actions should therefor be client side. Maintenance is more difficult when the code of JavaScript can be found within a PHP page. Create an .js file instead, make a function call returning what is in doc_add.php and go for it.
3 Comments
<a href='index.php?main=add-doc' class='footer-img' onclick=\"return confirm('Do you really want to go?');\">. Its not inside my PHP anymore.if($_GET["main"]=="add-doc"){
echo "<script>
var r=confirm(\"Press a button\");
if (r==true)
{
" . require_once('doc_add.php') . "
}
else
{
x=\"You pressed Cancel!\";
}
</script>";
}
Comments
First you need to understand that PHP is a server-side script, and javascript is a client-side script. This means that once the PHP script finishes rendering the HTML file, it cannot do any more actions.
What you can do, is dynamically render the javascript content before javascript runs.
in your case:
<?php
if($_GET["main"]=="add-doc"){ ?>
<script>
var r=confirm("Press a button");
if (r==true)
{
<? require_once(\"doc_add.php\"); ?>
}
else
{
x="You pressed Cancel!";
}
</script>
<?php
}
?>
1 Comment
Just echo the additional part.
By the way, you could use ' for echo so that you don't have to escape the " in javascript. (Although " and ' quotes in PHP are slightly different, it works functionally in this case.) Or you could use ' inside the javascript.
<?php
if($_GET["main"]=="add-doc"){
echo '<script>
var r=confirm("Press a button");
if (r==true)
{';
require_once("doc_add.php");
// Make sure the file returns valid javascript
echo '}
else
{
x="You pressed Cancel!";
}
</script>';
}