With AJAX I am getting data from a db sent back to the website as an json array. I get to put the result out to be displayed, but when I am going to use the data further, it says ReferenceError. variable is not defined. I can't see what I am doing wrong.
I am supposed to use the data from a object to put it as a parameter in a button for deleting (later), but in the code below I tried just to get the data inside the alert function to see if it worked. But somehow that does not work.
Here is my main code: (English is not my programming language. Sorry. Tried to translate what was possible)
function find()
{
url = "tjener-kode.php";
$.get(url,function(data){
var html="";
var dataen=JSON.parse(data);
console.log(dataen);
var postnumber="";
var postplace="";
for (var a=0; a < dataen.length; a++){
postnumber=dataen[a].postnr;
postplace=dataen[a].poststed;
html+="Postplace: "+postplace+" Postnumber: "+postnumber+" <button onClick=alarm("+dataen[a]["poststed"]+")>Test</button><br>";
}
$("#respons2").html(html);
});
}
function alarm(postplace){
alert("Hello. You clicked on "+postplace);
}
</script>
</head>
<body>
<p id="respons2"></p>
<button onClick="find()">Bring all postcodes</button>
</body>
</html>
For the button I have tried different code with the same error result:
<button onClick=alarm("+postplace+")>
<button onClick=alarm("+dataen[a]["poststed"].value+")>
Here is my server code tjener-kode.php:
<?php
$db = new mysqli("xxxxxxxxxxxxxxxxxx");
if($db->connect_error)
{
die("Error");
}
$sql = "Select * from postnrPoststed";
$resultat = $db->query($sql);
$data=array();
while($rad=mysqli_fetch_assoc($resultat)){
$data[]=$rad;
}
echo json_encode($data);
?>
Using console log you can see that the result is this. And this is correct: enter image description here
But when clicking the button at the webpage belonging to each object, with the supposedly defined variable, I get this error in the console:
It says that the variable is not defined, but somehow I still get the data in the variable shown in the console log.
enter image description here