+ 2
How to echo on the same page?
When I use echo it creates a new blank page and displays the text in there. How can I make it to display on the same page? This my my code here: <?php function printSomething(){ echo "Sorry. Forgive me please."; } ?> <html> <img src="cheese.jpg" onClick="document.write('<?php printSomething(); ?>');" /> </html>
8 Answers
+ 9
You can mix Php and JS, but you must know many things:
(+) your Php code will be executed once, when sending the generated Html ( else, you have to use Ajax as suggested by @Mohammad Apel Mahmoud, wich in your case will look as:
<html>
<img src="cheese.jpg" onClick="document.write('Suck my nose sideways!');" />
</html>
(+) you are outputting Html with JS, with the document.write() method, wich is expected to have executed document.open() for start writting a new web page... so, except if you use it at parsing time ( when the browser analyze the page -- ie. when it create the document after loading ), if you ommit the open() method, JS do it iimplcitly for you ^^
So, instead document.write(), for avoid clearing the page and output on same content, you need to use the 'innerHTML' r/w property of any html container elements ( ie: not those who are always empty: <br>, <hr>, <img>... )... Simplest way to append new content:
document.body.innerHTML += '<p>Suck my nose sideways!</p>';
However, other ways to inject/modify/read content dynamically with JS exists... among which the 'textContent', or the 'value' attribute of <input> elements: dive into Html references to explore and learn subtilities among each use ;)
+ 4
you are messing up Javascript with PHP.
Use only one or use ajax if you want to get the output from PHP
+ 4
@MM1132 please edit your comment. you already got one down vote. I don't want to down vote too, so remove inappropriate word
+ 2
not true try @apel look at +=
+ 1
Why do you want to use PHP?
+ 1
Thanks. Why can't I give you +1 tho? I haven't gotten any emails :D
0
try this
<?php
function printSomething(){
echo "Suck my nose sideways!";
}
?>
<html>
<body>
<script>
function chessebutton(){
document.body.innerHTML+="<?php printSomething(); ?>";
}
</script>
<img src="cheese.jpg" onClick="chessebutton();" />
<body></html>
- 1
Thank you so much ;)