Awani
Awani

Reputation: 394

Storing value of PHP variable in javascript variable

I'm trying to pass a php variable to a javascript variable(on different files).

myPHP.php

<?php
include'myJS.php';
$hello="Hello";
echo json_encode($hello);  

myJS.php

<html>
<head>
    <title>Hello</title>
    <script>
        var data;
        var oReq = new XMLHttpRequest();
        oReq.onload = function () {
            data = this.responseText;

            alert(data);
        };
        oReq.open("get", "myPHP.php", true);
        oReq.send();
    </script>
</head>
</html>

I'm running the myPHP.php file (and not myJS.php). I'm not getting any error, however, in the variable 'data' in myJS.php file, instead of storing the value of only the PHP variable, the entire myJS.php file is getting stored. How can I avoid this and store just the variable value?

P.S. This is a sample code, I would be implementing this logic with dynamic data, so please do suggest me solutions which can work with dynamic data.

Upvotes: 1

Views: 2310

Answers (1)

user4035
user4035

Reputation: 23729

You don't need ajax for static data, just generate javascript:

<?php
$hello="Hello";
?>

<html>
<head>
    <title>Hello</title>
    <script>
        var data = "<?php print $hello; ?>";
    </script>
</head>
</html>

If the data is not static, and you want to use ajax, separate the files:

myJS.php:

<html>
<head>
    <title>Hello</title>
    <script>
        var data;
        var oReq = new XMLHttpRequest();
        oReq.onload = function () {
            data = this.responseText;
            alert(data);
        };
        oReq.open("get", "myPHP.php?ajax=1", true);
        oReq.send();
    </script>
</head>
</html>

Here is myPHP.php:

<?php
if(!isset($_GET['ajax']))
{
    include('myJS.php');
}
else
{
    $hello="Hello";
    echo json_encode($hello);  
}

Upvotes: 4

Related Questions