I'm trying to return a while loop from an AJAX request, whilst also returning other data.
Basically i'm currently returning 3 or 4 sets of data from php requests, and passing them into my application on return. But I need to be able to loop through one of the sets of data to print to a table.
All of my code is working, i'm not getting any errors, its just not returning my devices array correctly.
I'm very close, and I think I know what my problem is, i just cant think at the moment how to solve it.
Javascript
function getDataViaAjax(id, days) {
$.ajax({
url: 'assets/processes/getWebsiteStatsData.php', // URL of php command
type: 'POST', //TYPE
data: {'id': id, 'days': days}, //Variables in JSON FORMAT
success: function(results) {
//SUCCESSFUL REQUEST FUNCTION
var result = $.parseJSON(results);
document.getElementById("websiteStatisticsDiv").style.display = "block";
document.querySelector("#websiteStatisticsURL > strong").innerHTML = result.dataArray.url;
document.querySelector("#websiteStatisticsBounceRate").innerHTML = result.dataArray.bounceRate;
document.querySelector("#websiteStatisticsDiv > div > div.col-lg-4.col-md-4.col-sm-12.col-xs-12.left > div > div").style.width = result.dataArray.bounceRate;
document.getElementById("websiteStatisticsConversionRate").innerHTML = result.dataArray.conversionRate;
document.querySelector("#websiteStatisticsDiv > div > div:nth-child(2) > div > div").style.width = result.dataArray.conversionRate;
var arrayLength = result.phonesArray.device.length;
for (var i = 0; i < arrayLength; i++) {
document.getElementById("arrayTest").innerHTML = JSON.stringify(result.phonesArray.device);
}
}
}); // end ajax call
};
PHP
<?php
include "../includes/includes.php";
$id = $_POST['id'];
$conversionRateDays = $_POST['days'];
$getSites = $db->query_assoc("SQL QUERY GOES HERE");
$getBounceRate = $db->query_assoc("SQL QUERY GOES HERE");
$getConversionRate = $db->query_assoc("SQL QUERY GOES HERE")
$getPhoneResults = $db->query_assoc("SQL QUERY GOES HERE");
$url = $getSites['main_url'];
$bounceRate = $getBounceRate['result'];
$conversionRate = $getConversionRate['result'];
$dataArray = array('url' => $url,'bounceRate' => $bounceRate, 'conversionRate' => $conversionRate);
$results = array('dataArray' => $dataArray, 'phonesArray' => $getPhoneResults);
echo json_encode($results, JSON_FORCE_OBJECT);
?>
At the moment if I run
console.log(result.phonesArray.device);
it only returns my first row of the database, but if I run it in a for loop like this
for (var i = 0; i < arrayLength; i++) {
console.log(result.phonesArray.device[i]);
}
it returns single letters of the first row. E.g, my first row is iPhone, the above command will loop through and log each letter as separate objects.
I'm thinking that I need to save each of the rows returned as a seperate array objects like device, device1, device2, device3, device4, because its saving over the device array name each time and only returning 1 result.
Any help would be appreciated!