Tryed to find my answer in many forums, found one main answer but for some reason doesn't work in my case.
Quite new to Web development. I'm trying to write a very simple JS program which consumes a list of products (presented by a JSON string), and returns an HTML table with the products. In order to use DB data, I'm using AJAX. So far I've got two files, a PHP and a JS file.
The page on the server called by the JS file (show.js) is a PHP file called "testmysql.php".
The problem is I've got a shared parameter in both files, and therefore I need to include the JS file in the PHP file.
**"show.js" : **
<html>
<head>
<script>
function showUser(str) {
if (str == "") {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("txtHint").innerHTML = xmlhttp.responseText;
}
};
xmlhttp.open("GET","testmysql.php?q="+str,true);
xmlhttp.send();
}
}
</script>
</head>
</html>
**"testmysql.php" : **
<html>
<head>
<script type="text/javascript" src="show.js"></script>
<style>
table {
width: 100%;
border-collapse: collapse;
}
table, td, th {
border: 1px solid black;
padding: 5px;
}
th {text-align: left;}
</style>
</head>
<body>
<?php
//Sample Database Connection Script
//Setup connection variables, such as database username
//and password
$hostname="localhost";
$username="root";
$password="";
$dbname="grocery";
$usertable="grocery";
$yourfield = "NAME";
$q = intval($_GET['q']);
//Connect to the database
$connection = mysqli_connect($hostname, $username, $password);
mysqli_select_db($connection, $dbname);
$query="SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($connection,$query);
echo "<table>
<tr>
<th>Name</th>
<th>Price</th>
<th>Amount</th>
</tr>";
if($result){
while($row = mysqli_fetch_array($result)) {
echo "<tr>";
echo "<td>" . $row['NAME'] . "</td>";
echo "<td>" . $row['PRICE'] . "</td>";
echo "<td>" . $row['AMOUNT'] . "</td>";
echo "</tr>";
}
}
echo "</table>";
mysqli_close($connection);
/*
//Setup our query
//$query = "SELECT * FROM $usertable";
Run the Query
$result = mysqli_query($connection,$query);
//If the query returned results, loop through
// each result
if($result)
{
while($row = mysqli_fetch_array($result))
{
$name = $row["$yourfield"];
echo "Name: " . $name;
}
}
*/
?>
</body>
</html>
The problematic row is script type="text/javascript" src="show.js">, and for some reason it returns the error of Undefined index: q, while q is the shared parameter in both files. Hope my question is comprehensible, appreciate it.