On my HTML page I have a script that sends a database query via PHP. Now I need to pass the array with the results (an associative array) back to my HTML page to populate some textareas.
Questions (I am new to PHP):
1- Can the array be passed as it is or it needs to be encoded/decoded or serialized/unserialized (and how)?
2- Once the array reaches the HTML script can I cycle through its elements via a loop (I mean, is it possible to make a loop inside an HTML script?)
3- If the latter is not possible, how could I then instruct PHP to populate a given textarea on the HTML page?
Edited (now with code):
//HTML
<script>
function PopulateTextAreas()
{
var arrayTextAreasNames = ["name","surname","dob"];
//Now pass this to php
var xhttp = new XMLHttpRequest();
var jsonstring = JSON.stringify(arrayTextAreasNames);
var encoded = encodeURIComponent(jsonstring);
xhttp.open("GET", "LoadFromDb.php?hId=" + "&arrayTextAreasNames=" + encoded, true);
xhttp.onreadystatechange = function()
{
if (this.readyState == 4 && this.status == 200)
{
var decoded = json_decode(this.responseText);
console.log(decoded); //Not working
//A loop would then follow to separate each element of the array and then populate the corresponding textareas is a way similar to below:
//document.getElementById("name").value = this.responseText;
//document.getElementById("surname").value = this.responseText;
//document.getElementById("dob").value = this.responseText;
}
};
xhttp.send();
}
</script>
//PHP
//The associative array is built in a loop like this
$ArrayDbEntryName_and_itsValue[$i] [$DbItemName] = $DbItemValue;
//and it looks like the follow one:
array(3) {
[0]=>
array(1) {
["name"]=>
string(1) "paul"
}
[1]=>
array(1) {
["surname"]=>
string(2) "green"
}
[2]=>
array(1) {
["dob"]=>
string(8) "1/1/1980"
}
//Then the array is echoed back to the HTML page like this
$ResultStringified = JSON.stringify($ArrayDbEntryName_and_itsValue);
echo encodeURIComponent($ResultStringified);