Good evening everyone. I know this will seem like an extremely easy subject for many here, but I've been struggling for a while to reconstruct a function I have in order to make it dynamic and reusable site-wide.
The main struggle I'm having is returning an Array using the following:
var arr = getData("admin/fullDatabaseAccess.php");
This doesn't return the array as expected. Now, without writing every possible variation of what I did to the getData function in an attempt to return the array which it creates, I'll first show you the original function which works:
function getData() {
var xmlhttp = new XMLHttpRequest();
var url = "admin/fullDatabaseAccess.php";
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
processResponse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
var arr = JSON.parse(response);
// do stuff with the array - I originally modified the DOM using jQuery here, however I now want to use this entire getData function as a more generically useful function
}
}
I would then trigger the getData function on the single page which I was using this code with to generate an array, followed by modifying the page elements with the array data.
THIS BRINGS ME TO MY PROBLEM - I tried to make this function re-usable across the site by creating this version below, and calling the array data using the code line I posted at first (var arr = ..):
function getData(file) {
var xmlhttp = new XMLHttpRequest();
var url = file;
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
processResponse(xmlhttp.responseText);
}
}
xmlhttp.open("GET", url, true);
xmlhttp.send();
function processResponse(response) {
var arr = JSON.parse(response);
return arr;
}
}
I cannot seem to feed the data back to the variable. I've tried restructuring the function quite a lot to return values within the nests etc but I've got to the point where I'm confusing myself and can't really show the examples I tried as I deleted them and decided to start again.
Any help would be greatly appreciated!!