I’m really struggling with this task for my course and hope someone doesn’t mind helping out or just offering guidance here. Basically I’m trying to create a simple Javascript XML Http Request to display basic information (the country_name & country_capital fields) from the database just in the html page. Below I just describe the apparent stages from the guide, and what I have done.
Firstly the ‘database.html’ page contains javascript XHR code which I think is mostly correct, but may have an error. To be honest I’m not 100% sure what else it does other than somehow refer to the getcountries.php file.
Secondly the getcountries.php file is where I’m really struggling as I’ve never coded in PHP. I think it’s supposed to fetch the data from the local server (I’m running XAMPP) and echo the results on the web page.
The database on phpMyAdmin is simple with just a table of countries including a primary key ID number, the country name, capital and currency, with the details below: Database name = countries_db Table name = countries_table Table fields: country_ID (primary key) country_name country_capital country_currency An example entry: 2, USA, Washington DC, US Dollar
To summarise, my question is this: how can I edit what I’ve done to correctly fetch the data from the database and display it on the page?
Really appreciate any help or advice here, thanks a lot.
<!-- Code on Page 1 (database.html) -->
<p id="txtHint"></p>
<p id="hint"></p>
<script>
function showUser(str) {
if (str=="") {
document.getElementById("txtHint").innerHTML="";
return;
}
if (window.XMLHttpRequest) { // detects whether the browser has XMLHttpRequest functionality
// code for modern browsers
xmlhttp=new XMLHttpRequest(); // creates an XMLHttpRequest object
} else { // code for old browsers
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() { // onreadystatechange defines the function to be called when the readyState property changes
if (this.readyState==4 && this.status==200) {
document.getElementById("hint").innerHTML=this.responseText;
}
}
xmlhttp.open("GET","getcountries.php?q="+str,true);
xmlhttp.send();
}
</script>
<!-- Code on Page 2 (getcountries.php) -->
<?php
$q = intval($_GET['q']);
$con = mysqli_connect('localhost','root','');
if (!$con) {
die('Could not connect: ' .mysqli_error($con));
}
mysqli_select-db($con,"countries_db");
$sql="SELECT country_name AND country_capital FROM records";
$result = mysqli_query($con,$sql);
echo "Results:"
error_reporting(E_ERROR | E_PARSE);
\
while($row = mysqli_fetch_array($result)) {
echo $row['country_name'] . "<br>";
echo $row['country_capital'] . "<br>";
}
mysqli_close($con);
?>
</div>