Trying the create a javaScript array from a PHP array of urls to images using JSON and AJAX. Then I want to display the images on a cordova app. I believe my issue is I'm either I'm receiving or sending the Json messages with automatic html tags. My xmlhttp.response is equal the array of urls but it has html tags which are not present in the PHP file. I think because of these tags my JSON.parse isn't working?
This is my PHP stored on a server. I'm returning the urls in 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 json_encode($data);
?>
This is my script in my cordova app. I want to covent the JSON message into a javaScript array and display the first image in the array in the div contents. But I think I'm calling a message which includes html tags so I can't parse the message I could be wrong. I currently get three error alerts because the ready state is not correct.
<html>
<script>
var arr = [];
function importJson(str) {
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 && xmlhttp.status == 200){
alert(xmlhttp.response);
arr = JSON.parse(xmlhttp.response);
//var arr = (array)json.parse(xmlhttp.response);
for (var i = 0; i < arr.length; i++) {
buildImage(arr[i]);
alert(arr[0]);
}
} else {
alert("Error");
}
}
xmlhttp.open("GET","http://server/~name/folder/content.php);
xmlhttp.responseType = "json";
xmlhttp.send();
buildImage=function(src) {
var img = document.createElement('img');
img.src = src;
document.getElementById("content").appendChild(img);
}
}
window.onload = importJson();
</script>
<body>
<div id="content"></div>
echo json_encode($data)
? – i alarmed alien Aug 23 '14 at 13:24