After spending a significant amount of time searching online, I have not been able to find a working solution to achieve what I need.
Essentially, I am making an AJAX request that executes a database query and then outputs the results using echo json_encode($row);
Once this JSON data is returned to my JavaScript, I am facing some challenges. I need to parse the JSON array and extract specific elements to dynamically update input field values. Below is the code snippet I am using to make the AJAX request and receive the JSON array:
var vars = new XMLHttpRequest();
vars.onload = function() {
var retrieved = new Array(this.responseText);
document.getElementById("testingOutput").innerHTML = retrieved;
};
vars.open("GET", "https://my.url.here", true);
vars.send();
I have attempted a few methods to extract data from the array without success (I am relatively new to JavaScript). For example, I tried accessing the data using keys like retrieved['first_name']
and indexes like retrieved[1]
, but none of these worked. I also experimented with 'for' loops, but couldn't get them to function as expected.
Ultimately, I simply need a way to extract specific data from the array to use in jQuery as shown below:
$("#firstname").val = forename;
$("#lastname").val = surname;
Any assistance would be greatly appreciated as I am feeling quite frustrated at this point!
EDIT: Initially, I tried setting
var retrieved = (this.responseText);
, which resulted in the data being detected as a string when checked with typeof
. On the other hand, var retrieved = new Array(this.responseText)
indicated that the type was an object. I am unsure of how to access the data in either case.