简体   繁体   中英

How to pass PHP data to external JavaScript

I want to pass a variable, or rather a message, from my PHP file to my external JavaScript file. I have looked at other answered questions and it seems like the PHP file is not really full PHP, it has some js codes in it.

I just want to pass a simple message so I can use alert() in the external js to show the message.

Should I use JSON(which I do not know how)? Or is there a simpler way? I am new to all these so perhaps a simple explanation with an answer without jQuery would be appreciated.

In the PHP file:

function checkDuplicateTesterName($tester_name)
{
    $table_info = "TBL_TESTER_LIST";
    $query_string = "select tester_name from $table_info where tester_name = $tester_name";
    $result = @mysql_query($query_string) or die (mysql_error());
    $checkTester = mysql_num_rows($result);
    if($checkTester>0)
    {
        echo $message = "Error, please check again."; //I want to pass this
    }
}

In the external js file:

function checkTester()
{
    var tester_name = document.getElementById("tester_name").value;
    var page = "database.php";

    var parameters = "&tester_name="+tester_name+"&action=check";
    var xmlhttp = new XMLHttpRequest();

    if(xmlhttp==null)
    {
        alert("Your browser does not support ajax!");
        return false;
    }
    xmlhttp.onreadystatechange=function()
    {
        if(xmlhttp.readyState==4)
        {
            alert("function success."+message); //Alert error message from PHP here
        }
    };
    xmlhttp.open("GET", page+"?"+parameters, true);
    xmlhttp.send(null);
}

The response is in the responseText field of the XHR object, so you need to do:

xmlhttp.onreadystatechange=function()
{
    if(xmlhttp.readyState==4)
    {
        var message = xmlhttp.responseText;
        alert("function success."+message); //Alert error message from PHP here
    }
};

You don't need to use JSON if you're just returning a string. JSON is useful if you're returning an array or object.

You can do it by defining global variable which value comes from php like this one below.

<script type="text/javascript">
   var message = '<?= $message ?>';
</script>

That is the simple way.

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