I am a beginner and I am trying to echo arrays and append them into a html division i created. The AJAX call I made was successful but the response was not appearing inside the division i assigned it to. Upon further inspection, I found out that the response I have received has an array length over 600 ( I am expecting 10 records). So there must be something wrong with my echo PHP file or the receiving end of the HTML file but just cannot figure out what that is.
Here are my codes:
listdiscount.php
<?php
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
$conn = new mysqli("localhost", "root", "root", "bencoolen");
$userid = $_GET['userid'];
$result = $conn->query("select userid, codename from discountcode where userid ='" . $userid . "' ");
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
printf("Userid: %s '' Codename: %s", $row["userid"], $row["codename"]);
}
$conn->close();
?>
index.html ( with js codes )
<html>
<script>
function mydiscount(){
var userid = "jimmy";
var xmlhttp = new XMLHttpRequest();
var url = serverURL() + "/listdiscount.php";
url += "?userid=" + userid;
alert(url);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
alert("readystate=4 and status =200");
mydiscountresult(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
function mydiscountresult(response) {
var arr = response;
alert(arr); //alerted
alert(arr.length); //alerted 600+ arrays
alert("mydiscountresult working"); //alerted
var i;
$("#discountcontent").empty();
for(i = 0; i < arr.length; i++) {
$("#discountcontent").append("<b>" + arr[i].userid + "</b>"+ arr[i].codename + "<hr>");
}
}
mydiscount();
</script>
<div data-role="content" class="ui-content" id="discount">
LIST OF DISCOUNT CODE:<br>
<div id="discountcontent" class="ui-grid-solo">
</div>
</div>
</html>
Here is what my response look like when alerted:
addition note: my php files are in different folder so serverurl() is declared and used here.