I'm aware that there are similar questions, however, I have a few issues with them, as they mentioned a few possibilities and I'm not sure which one is best for my situation.
I have a form that has one section where you can enter the name of an xml-file, which is then generated using php. The name of the file is stored in a variable using php. In order to access the xml-file, I wanted to retrieve the value of the php-variable in JavaScript. According to what I read, there are a few possibilities:
An Ajax-request. My problem: I tried to follow this tutorial (https://www.w3schools.com/xml/ajax_php.asp). I don't fully understand this tutorial though.
First of all, in the first example, what is "this"? (e.g this.responseText)
Secondly, why is it "gethint.php?q=" + str instead of simply "gethint.php" (in xmlhttp.open())?
- Finally, what does $q = $_REQUEST["q"]; tell me exactly? I know that some kind of a variable is declared but I don't understand what is does exactly.
I also read that you could use cookies, but would that make sense in my instance? Please let me know if you need further information and thank you very much in advance for your replies.
Edit: Here's the code I tried to follow: HTML:
<html>
<head>
<script>
function showHint(str) {
if (str.length == 0) {
document.getElementById("txtHint").innerHTML = "";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("txtHint").innerHTML = this.responseText;
}
};
xmlhttp.open("GET", "gethint.php?q=" + str, true);
xmlhttp.send();
}
}
</script>
</head>
<body>
<p><b>Start typing a name in the input field below:</b></p>
<form>
First name: <input type="text" onkeyup="showHint(this.value)">
</form>
<p>Suggestions: <span id="txtHint"></span></p>
</body>
</html>
PHP:
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
// Output "no suggestion" if no hint was found or output correct values
echo $hint === "" ? "no suggestion" : $hint;
?>
$a is an array of names, which I did not include in the extract in order to save space.
Here's my code:
HTML:
<body onload="alertFunction()">
<h1 id="title">Append to me:</h1>
<p id="paragraph"></p>
</body>
JavaScript:
function alertFunction() {
var xhttp;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var filename = xhttp.responseText;
alert(filename);
}
};
xhttp.open("GET", "profile3.php?q=", true);
xhttp.send();
};
PHP:
<?php
$q = $_REQUEST["q"];
echo $filename
?>
$filename is declared to be the name of my xml-document. I did not include that piece of code because I know that that's not the problem.