I am looking for a way to use HTML file/ajax code to extract the JSON message and store the PATHS as a JavaScript array. This will allow my buildImage function to display the first image in the array. I am new to AJAX and suspect that my issue lies in converting the JSON to JavaScript. Also, I am unsure whether my code generates a JSON array or object. Should I consider downloading a library to help me understand JSON better?
Below is a PHP file that loads the paths of the images. It seems like json_encode is converting the PHP Array into a JSON message.
<?php
include("mysqlconnect.php");
$select_query = "SELECT `ImagesPath` FROM `offerstbl` ORDER by `ImagesId` DESC";
$sql = mysql_query($select_query) or die(mysql_error());
$data = array();
while($row = mysql_fetch_array($sql,MYSQL_BOTH)){
$data[] = $row['ImagesPath'];
}
echo $images = json_encode($data);
?>
Below is the script that will be loaded on a Cordova app.
<!DOCTYPE html>
<html>
<head>
<link rel="stylesheet" href="css/styles.css">
<link rel="stylesheet" href="css/cascading.css">
<script>
function importJson(str) {
// console.log(typeof xmlhttp.responseText);
if (str=="") {
document.getElementById("content").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
//var images = JSON.parse(xmlhttp.responseText);
document.getElementById("content").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","http://server/content.php");
xmlhttp.send();
}
function buildImage(src) {
var img = document.createElement('img')
img.src = src
alert("1");
document.getElementById('content').appendChild(img);
}
for (var i = 0; i < images.length; i++) {
buildImage(images[i]);
}
</script>
</head>
<body onload= "importJson();">
<div class="contents" id="content" ></div>
<img src="img/logo.png" height="10px" width="10px" onload= "buildImage();">
</body>