So I've got a form where I can create multiple datalist-text-inputs of the same type that is later (onclick) put into an invisible input before submitted.
These datalist-text-inputs is created onload so that I can add more with an "+" button with the same function.
The options are imported from my PHP-database, and it worked fine. But suddenly it stopped working and I don't know why. I've tried a thousand things but can't figure it out.
I'm quite new to PHP. I think the problem has to do with JSON.parse() since the code breaks on that line.
script.js
var ajax = new XMLHttpRequest();
ajax.open("GET", "fetch data.php", true);
ajax.send();
ajax.onreadystatechange = function() {
if(this.readyState == 4 && this.status == 200) {
var data = JSON.parse(this.responseText);
var html = "";
for (var a = 0; a < data.length; a++) {
var firstName = data[a].name;
html += "<option value='" + firstName + "'></option>";
};
document.getElementById(type+"list"+addnumber).innerHTML = html;
};
};
type+"list"+addnumber it the name of the input-text-box. Type is an argument and addnumber an variable/integer.
fetch data.php
<?php
$host = "localhost"; $user = "root"; $pass = ""; $db = "collection";
$conn = mysqli_connect($host, $user, $pass, $db);
$result = mysqli_query($conn, 'SELECT name FROM musicians ORDER BY name');
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$data[]=$row;
};
echo json_encode($data);
?>
Also, I might add that this function creates objects in three places on the same page but the value is added/moved to three different invisible inputs.