tags:

views:

1038

answers:

4

Hi friends,

I want to use the php variable in javascript. How its possible?

Please help me..

+10  A: 

You can print the PHP variable into your javascript while your page is created.

<script type="text/javascript">
    var MyJSStringVar = "<?php Print($MyPHPStringVar); ?>";
    var MyJSNumVar = <?php Print($MyPHPNumVar); ?>;
</script>

Of course this is for simple variables and not objects.

Gary Willoughby
And you might want to do some sanity checking, make sure the PHP variables what you want before you output them, otherwise you'll have some zany Javascript errors.Also don't forget to sanitize, make sure the variable doesn't contain ", you need to HTMLEncode it or use JSON.
TravisO
+1  A: 

You can pass PHP Variables to your JavaScript by generating it with PHP:

<?php
$someVar = 1;
?>

<script type="text/javascript">
    var javaScriptVar = "<?php echo $someVar; ?>";
</script>
Karsten
+4  A: 

It depends on what type of PHP variable you want to use in Javascript. For example, entire PHP objects with class methods cannot be used in Javascript. You can, however, use the built-in PHP JSON (JavaScript Object Notation) functions to convert simple PHP variables into JSON representations. For more information, please read the following links:

You can generate the JSON representation of your PHP variable and then print it into your Javascript code when the page loads. For example:

<script type="text/javascript">
  var foo = <?php echo json_encode($bar); ?>;
</script>
William Brendel
+3  A: 

I think the easiest route is to include the jQuery javascript library in your webpages, then use JSON as format to pass data between the two.

In your HTML pages, you can request data from the PHP scripts like this:

$.getJSON('http://foo/bar.php", {'num1': 12, 'num2': 27}, function(e) {
    alert('Result from PHP: ' + e.result);
});

In bar.php you can do this:

$num1 = $_GET['num1'];
$num2 = $_GET['num2'];
echo json_encode(array("result" => $num1 * $num2));

This is what's usually called AJAX, and it is useful to give web pages a more dynamic and desktop-like feel (you don't have to refresh the entire page to communicate with PHP).

Other techniques are simpler. As others have suggested, you can simply generate the variable data from your PHP script:

$foo = 123;
echo "<script type=\"text/javascript\">\n";
echo "var foo = ${foo};\n";
echo "alert('value is:' + foo);\n";
echo "</script>\n";

Most web pages nowadays use a combination of the two.

csl
I think you just confused him. I don't think he was expecting anything nearly that complex.
jdelator
Yes, I see your point — maybe he could've tried to explain more what he wanted.
csl
I'm not sure including the entire library to use the JSON function is the best way to go. There are a lot of alternatives to jQuery for that particular task.
Salty
You're right. A lightweight library that just wraps the xml-http talking would be neat.
csl