Could someone please explain why the following code works:

<html>
<head>
<script type="text/javascript">
        function test(){
         phpTest = "<?php echo \'hello\'; ?>";
         document.getElementById("php_code").innerHTML = phpTest;
        }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
</body>
<html>

while this code doesn't:

<html>
<head>
<script type="text/javascript">
        function test(){
         phpTest = "<?php echo \'hello world\'; ?>";
         document.getElementById("php_code").innerHTML = phpTest;
        }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
</body>
<html>

(NB: the only difference is, that the first string says 'hello', and the second 'hello world')

Member Avatar for P0lT10n

dont work because you didnt use "\'Hello World\'" and because you have spaces between hello world it wont work... put "" before the firts \ and the last ' and will work...

<html>
<head>
    <script type="text/javascript">
    function test(){
       phpTest = "<?php echo "\'hello world\'"; ?>";
       document.getElementById("php_code").innerHTML = phpTest;
    }
    </script>
</head>
<body>
    <a href="#" onclick="test(); return false;"> test </a>
    <span id="php_code"> </span>
</body>
<html>

Don't forget that is:

echo "message";
or 
echo $var;

Could someone please explain why the following code works:

<html>
<head>
<script type="text/javascript">
        function test(){
         phpTest = "<?php echo \'hello\'; ?>";
         document.getElementById("php_code").innerHTML = phpTest;
        }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
</body>
<html>

while this code doesn't:

<html>
<head>
<script type="text/javascript">
        function test(){
         phpTest = "<?php echo \'hello world\'; ?>";
         document.getElementById("php_code").innerHTML = phpTest;
        }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"> </span>
</body>
<html>

(NB: the only difference is, that the first string says 'hello', and the second 'hello world')

according to me both of your code should not word

you are doing <?php echo \'hello'\; ?>
trying to escape ' but this will give an error Unexpected character in input: '\'

try <?php echo 'hello'; ?>
as you have already included ""

Member Avatar for P0lT10n

according to me both of your code should not word

you are doing <?php echo \'hello'\; ?>
trying to escape ' but this will give an error Unexpected character in input: '\'

try <?php echo 'hello'; ?>
as you have already included ""

... i thought that he was trying to show 'Hello' not Hello... i know how to show text or something in PHP... if he want to show 'Hello' its <? echo "\'Hello\'"; ?> if not <? echo "Hello"; ?>...

Right. Thanks a lot guys. Now that the most primitive 'hello world' version of my intended program works, please have a look at the following, slightly more advanced example. Why does this not work?

<html>
<head>
<script type="text/javascript">
  function test(){
    document.getElementById("php_code").innerHTML = "<?php echo file_get_contents('./test.txt') ; ?>";
  }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"></span>
</body>
<html>

Where the contents of test.txt is simply "hello world" (without quotation marks).

Your help is much appreciated.

Member Avatar for P0lT10n

i never used file_get_contents but i think that the firs . is bad. i mean '/test.txt' try this

No '/test.txt' doesn't work, and neither does 'test.txt'.

The following code gives the desired output:

<span id="php_code"><?php echo file_get_contents('./test.txt') ; ?></span>

So my php code is correct. But why doesn't it work when called from JavaScript?

As you're dealing with javascript, you can easily load the page up that's not working properly and view the source. Or even in most browsers, you can click and see if the javascript is erroring at all.

Just for curiosities sake, have you tried viewing the page source for the one where you echo in the file contents into the javascript instead of into the span?

Also for P0lT10n, file_get_contents() is really nice if you're only looking to grab the information out of the file:
http://php.net/manual/en/function.file-get-contents.php

Member Avatar for nevvermind
file_get_contents('./test.txt');
file_get_contents('test.txt');
// these are both the same thing because "./" refers to the "parent directory"

You don't "call it from a JavaScript". You just output text, as you could've done into a XML file just as well.
I've tested your code and it works. What browser are you using?

If you're using "innerText", read this: Using the innerText Property in Firefox.

Nyight's suggestion of viewing the html source after clicking the 'test' link is a good one. You can see I'm a newbie at debugging php. Here's the source code. I don't know why there is a carriage return as I didn't put one in 'test.txt'.

<html>
      <head>
      <script type="text/javascript">
      function test(){
      document.getElementById("php_code").innerHTML = "hello world
";
      }
      </script>
      </head>
      <body>
      <a href="#" onclick="test(); return false;"> test </a>
      <span id="php_code"></span>
      </body>
      <html>

I'm running my code in Firefox.

Found a solution that seems to work, using methods taken from this blog: http://tinyurl.com/26gw3y2

<html>
<head>
<script type="text/javascript">
      function test(){
           document.getElementById("php_code").innerHTML = "<?php $escaped_value = str_replace(chr(13),'n',file_get_contents('./test.txt'));             
$escaped_value = str_replace(chr(10),'',$escaped_value); echo $escaped_value ; ?>";
      }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"></span>
</body>
<html>

The added text basically replaces ascii line breaks into Javascript line breaks.

Final question. If I solve this, then I start coding in earnest. Why does the code in my previous post work, but the following code doesn't?

<html>
<head>
<script type="text/javascript">
      function test(){
           var fname = "./test.txt";
           document.getElementById("php_code").innerHTML = "<?php $escaped_value = str_replace(chr(13),'n',file_get_contents('" + fname + "')); $escaped_value = str_replace(chr(10),'',$escaped_value); echo $escaped_value; ?>";
      }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"></span>
</body>
<html>

The only difference is that the PHP command is made by concatenating three substrings. Here's the result:

<html>
<head>
<script type="text/javascript">
      function test(){
           var fname = "./test.txt";
           document.getElementById("php_code").innerHTML = "";
      }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"></span>
</body>
<html>

Clearly the PHP string following the innerHTML command hasn't been evaluated correctly. Any ideas?

To understand this error you'll need to understand when each peice of code is executed. Php is parsed entirely server side. This means that the client (the person viewing the page) never gets to see any of the php code (source). On the other hand, to my knowledge, javascript is only ever ran/parsed on the client.

With that in mind, fname is never defined within php so it's equivocally trying to run file_get_contents('""'); which will undoubtedly return an empty string.

[Note on server side js]
It would appear, after a quick google search, js server side is possible but not very popular and your host must have it installed, as it's an add-on for apache, for it to work. Though this is not very practical yet, in my opinion. http://www.webreference.com/programming/javascript/rg37/index.html

Right. Thanks a lot guys. Now that the most primitive 'hello world' version of my intended program works, please have a look at the following, slightly more advanced example. Why does this not work?

<html>
<head>
<script type="text/javascript">
  function test(){
    document.getElementById("php_code").innerHTML = "<?php echo file_get_contents('./test.txt') ; ?>";
  }
</script>
</head>
<body>
<a href="#" onclick="test(); return false;"> test </a>
<span id="php_code"></span>
</body>
<html>

Where the contents of test.txt is simply "hello world" (without quotation marks).

Your help is much appreciated.

again man you are not using the addslashes method as the file may contain a "

if you echo "hello "xyz"" then it will be a javascript error do escape the " in your code all te best

Okay, but it doesn't matter. Nyight is ryight: there doesn't seem to be an easy way to let JavaScript write PHP code.

Fortunately, I think I just found a way to do what I want to do using JavaScript only. I'll leave PHP alone for the time being. Learned a lot, though. Thanks for all your help!

this will work for you:

<script type="text/javascript">
      function test(){
      document.getElementById('php_code').innerHTML = '<?="hello world"?>
';
      }
      </script>
      
      <a href="#" onclick="test();"> test </a>
      <span id="php_code"></span>

Boss you are trying to embedd PHP code in javascript function.

Why don't you assign a "Hello" or "Hello World" to phptest only!!!

instead of trying to make a server call for no reason. Every server call harms your application performance...

Well, of course I wanted to do something more interesting than printing 'hello world'. My example code above was just a dumbed down version of a more elaborate piece of code which I wanted to write. My eventual aim was to develop a dynamic website in which the user would see certain html pages depending on a number of JavaScript buttons. The filenames would be stored in a Javascript array and then fed into php. But it turns out this is actually quite easy to do with JavaScript alone. In case anyone's interested, here's some code (again simplified for the sake of clarity):

<html>
<script type="text/javascript">
var i=0;
var fnames = ["foo.html","bar.html"];
function getPage(j){
    if (j>=0 && j<fnames.length){
        i=j;
        document.getElementById('test').innerHTML =
             "<object data=\"" + fnames[i] + "\" type=\"text/html\"";
    }
}
</script>
<body>
<div id="test"></div>
<button onclick='getPage(0);'>Foo</button>
</body>
</html>

I should also mention that you can reach the getPage() function from inside any iframe or object:

<html>
<body>
<a href="" onclick="location.href='javascript: window.parent.getPage(1);'">get me from foo.html to bar.html</a>
</body>
</html>

All this may seem trivial to you, but it wasn't to me a few days ago. In my struggle to get out of the iframe/object, I turned to php. Cheers.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.