2
<?php
header("Content-type: application/javascript");
?>
<!DOCTYPE HTML>
<html>
<head>
</head>
<body>
<?php 

   $variable=10;
?>
<script>

   var myVar = "<?php echo $variable; ?>";
   alert(myVar);

</script>
</body>
</html>

this is my source code and it is not working. My concern is converting the php variable as javascript variable..The alert displays the entire line as a string instead of printing the value...Have tried json function as well.No use.what should I be doing?

0

3 Answers 3

6

Remove this line:

header("Content-type: application/javascript");

This tells browser to output this page as text (i.e browser will not render it), JavaScript should be loaded into HTML files.

Sign up to request clarification or add additional context in comments.

1 Comment

or at least change it to text/html instead.
5

You should definitely not tell the browser that it's receiving JavaScript when it is in fact receiving HTML:

header("Content-type: text/html");

The fact that the HTML contains a <script> tag, which itself contains JavaScript is something entirely different.

Additionally, a much better way on injecting PHP variables in JavaScript is

var myVar = <?php echo json_encode($variable); ?>;

Note no quotes around the value -- json_encode quotes automatically as required. There are certain fine points about injecting variables that make both this one and your original approach not bulletproof, but json_encode is much better as a default choice.

4 Comments

in HTML5 the type attribute isn't necessary. js is assumed
@Bart: Neither are the double quotes the original had. What is your point? That it's better to judge on a case-by-case basis rather than be safe (well, much safer if not 100% safe) across the board?
@Jon my point is that the OP stated he tried json_decode already, and it's not relevant to this problem.
@Bart: That's why it's in the second half of the answer: it's not the main point. But it is IMHO important enough that it should be mentioned. Plain echo is just an invitation to break.
0

I guess your file has the .php extension. In this case, a simple <script>var myVar=<?php print $variable; ?></script> will do, no need to encase it in quotes or double quotes :P

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.