My purpose is to select data from MYSQL database using Javascript Fetch API. I can do it using AJAX as follows:
File ‘getUser.php’:
<?php
$con = mysqli_connect('hostname','username','password','database');
$q = intval($_POST['q']);
if ($con) {
$sql = "SELECT * FROM user WHERE id = '".$q."'";
$result = mysqli_query($con, $sql);
$row = mysqli_fetch_array($result)
if ($row) {
echo "$row[1]";
}
}
?>
File ‘index.php’:
<script>
function showUser(str) {
let xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
... = this.responseText;
}
};
xmlhttp.open("POST", "getUser.php");
xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlhttp.send("q="+str);
}
</script>
With Fetch API I tried this:
<script>
let file = "getUser.php";
fetch (file)
.then(x => x.text())
.then(y => ... = y);
</script>
But I cannot find how can I pass the value of ‘str’ to file ‘getUser.php’ so as to extract from the database the data for the specific person.