简体   繁体   中英

php variable to javascript (via json)

I know this has been discussed before but I can't seem to make anything work. I'm trying to pass the variable $thedate from PHP file mainclass.php to the variable datestr in a JS function from the file footer_script.php

JS:

function getsched(str)
{
    //some code
    $.ajax({
        type: 'POST',
        url: 'mainclass.php',
        data: 'date=' + str + '&form=getsched',
        success: function(data) {
            var datestr = <?php echo json_encode($thedate); ?>;
            $("#" + str).html(data);
        }
    }).error(function() {
        alert(data);
    });
}

PHP:

case "getsched":
    //some code
    //some query

    while($row = mysql_fetch_array($result))
    {
        //more code
        $thedate = $_POST['date'];
    }
    //other code here
break;

When I alert datestr , I get undefined . How to fix this?

You can't use PHP like this. You should obtain the response from PHP and use it. In your PHP, you should output a response similar to this (just an example of JSON response):

echo json_encode(array('thedate', '2018-4-3'));

and you can obtain the value of 2018-4-3 in your JS with:

function getsched(str)
{
    //some code
    $.ajax({
        type: 'POST',
        url: 'mainclass.php',
        data: 'date=' + str + '&form=getsched',
        success: function(data) {
            var datestr = data.thedate;
            $("#" + str).html(datastr);
        }
    }).error(function() {
        alert(data);
    });
}

You need to replace the line:

var datestr = <?php echo json_encode($thedate); ?>;

with

var datestr = JSON.stringify(date);
alert(datestr);

It will convert the server response to a JSON encoded string. The encoded string is then displayed in the alert. See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/stringify

Assign a global variable in HTML/PHP file before includeing JS file.

var datestr = <?php echo $thedate; ?>;

Then you can access the datestr variable from your JS file.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM