1

Possible Duplicate:
Pass a PHP string to a Javascript variable (and escape newlines)

I am quite new to the concepts of Javascript/jQuery and PHP. I have been using PHP implemented in Appserv for two weeks now to get data from a modbus device and store it in a csv file. Now i want to plot the data using jQplot. I am trying to write a simple program to first see if i can implement php and javascript code together in html. This is a code that i have written in html and uses both javascript and php.

<!doctype html>
<html>
<head>
<title>Demo</title>
</head>

<body>
<h2>This is a script</h2>
<script type="text/javascript">
    var out = <?php echo "Hello"?>;
    //var out = "Hello"
    document.write(out);
</script>

</body>
</html>

When i run this code in the browser ( I use google chrome with windows 7) I only get the heading "This is a script". However if i remove the line with the php code and uncomment the next line

var out = "Hello";

then the code prints the output with "Hello" like its supposed to. Why is this?

Community
  • 1
  • 1
Karthik Sai
  • 35
  • 1
  • 6

3 Answers3

5

You need add quotes around your PHP tags, like this:

var out = "<?php echo "Hello"?>";

Otherwise after PHP has parsed the file and output it it'll output like this:

var out = Hello;

... notice you're missing the quotes, JavaScript won't like that.

Ben Everard
  • 13,652
  • 14
  • 67
  • 96
0

I think you forgot to enclose your php code, as you give the value to your out variable :

    var out = <?php echo "Hello"?>;

Should be :

    var out = "<?php echo "Hello"?>";

Correct me if I'm wrong but I think this is where the issue comes from. :)

Edit : Looks like some people were faster than me anyway!

Cécile Fecherolle
  • 1,695
  • 3
  • 15
  • 32
0

I do agree with Ben Everard and Eddy Yuansheng Wu with a slight modification

This works:

var out = "<?php echo 'Hello'?>";

This doesnt work

var out = "<?php echo "Hello"?>";

Reason: using double quotes will consider it as end of string and js stops its functionality.

Tejesh
  • 189
  • 2
  • 12
  • "Reason: using double quotes will consider it as end of string and js stops its functionality" Not true, remember, PHP is back end, and thus the PHP script will be output `Hello`, nothing more. – Ben Everard Dec 13 '12 at 16:00
  • Guess you are right! Thanks Ben. – Tejesh Dec 14 '12 at 05:39