2

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);
}
1
  • Whats the issue in current code ? Commented May 26, 2015 at 0:52

2 Answers 2

3

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.

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

Comments

0

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.

3 Comments

That's not an external JS file.
yes, but you can reference to message variable from your external js file.
But it will be the value from when the page was loaded, not the value calculated during the AJAX request.

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.