Reputation: 475
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);
}
Upvotes: 2
Views: 618
Reputation: 781779
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.
Upvotes: 3
Reputation: 8443
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.
Upvotes: 0