I am passing an array of string from the file indexOnLoad.php
. After getting this with the help XMLHttpRequest()
in JavaScript when I return this array I get the variable as 'undefined'
.
The HTML code is:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="NavBar.css">
<link rel="stylesheet" href="indexCSS.css">
<script src="indexJS.js" charset="utf-8"></script>
<script type="text/javascript">
var arrayString;
</script>
<title>Find your Bus</title>
</head>`enter code here`
<body bgcolor=#81D4FA onkeypress="test();" onload="arrayString = indexOnLoad();console.log('arrayString ');console.log(arrayString);">
<ul class="NavBar">
<li class="NavBarList" id="Home">
<a href="#" style="text-decoration: none; color: white;">
Home
</a>
<div class="NavBarListContent" id="homeContent">
<a href="#">About</a>
<a href="#">Developers</a>
<a href="#">Suggestions Box</a>
</div>
</li>
<div style="float: right;">
<li class="NavBarList">
Administrator
</li>
</div>
</ul>
<div class="filler1">
</div>
<div class="SearchBox">
<input type="text" id="textBoxSearchQuery" placeholder="Search for Anywhere..." list="suggestions"><datalist id="suggestions">
<option value="Manan">Manan</option>
<option value="Anant">Anant</option>
</datalist><img src="search-89.png" name="buttonSearch" value="Search" id="buttonSearch">
</div>
</body>
</html>
Please take a look on the body tag and the script containing main problem code.
JavaScript file, which is named as "indexJS.js"
is:
function indexOnLoad() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
return obj;
}
};
xhttp.open("GET", "indexOnLoad.php", true);
xhttp.send();
}
The PHP file, which is named as "indexOnLoad.php" is:
<?php
$array = array("1","2","3");
$json = json_encode($array);
echo $json;
?>
the results after this in browser