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!
Figured it out, turns out I needed to re-create the array in PHP. As usual if I retrieved an associative array from the database and echo'd it out, it would only echo the first row, unless i ran it through a loop.
The array was working, it was simply only returning 1 result. I changed my php to
$getPhoneResults = $db->query("SQL QUERY GOES HERE");
$newDeviceArray = array();
while ($row = mysqli_fetch_assoc($getPhoneResults)){
$newDeviceArray[] = $row;
};
$url = $getSites['main_url'];
$bounceRate = $getBounceRate['result'];
$conversionRate = $getConversionRate['result'];
$dataArray = array('url' => $url,'bounceRate' => $bounceRate, 'conversionRate' => $conversionRate);
$results = array('dataArray' => $dataArray, 'phonesArray' => $newDeviceArray);
echo json_encode($results, JSON_FORCE_OBJECT);
and now when I run
console.log(result.phonesArray[0]);
It returns the row correctly.
It's hard to say without seeing what's actually in your phoneArray
variable, but it looks a little suspicious that you're doing:
var arrayLength = result.phonesArray.device.length;
Assuming (based on the name and that it's a result set from a database query) that the array you're trying to process is phonesArray
, shouldn't this be:
var arrayLength = result.phonesArray.length;
And then you'd access the members like:
for (var i = 0; i < arrayLength; i++) {
console.log(result.phonesArray[i].device);
}
?
I would start by checking the results from the database aka $getPhoneResults
by doing something like:
echo "<pre>"; var_dump($getPhoneResults); die();
And then call the php-script directly from a browser.
If the result seems correct, then check the console for the entire result of the AJAX-call before you start to loop over it:
console.log(result);
For the loop, you could try doing this with jQuery instead:
$(result).each(function(i,e){
//e.device
//i will be your iterator
});
By the way...by adding:
header("Content-type: application/json; charset=utf-8");
To your php-script before outputting data, your response type will be correct and you won't have to do this:
$.parseJSON(results);
Hope it helps.