I have scoured the internet looking for a working method to achieve what i need to, but had no luck so far.
Basically, I have an AJAX request which runs a database query and echo's everything into a json_encode function doo-dah -> echo json_encode($row);
Now, this is then passed back to my Javascript, and this is where i'm stuck. I need to access the JSON array and select various parts for use to alter input field values dynamically. This is the code i have to run the AJAX request and retrieve 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();
Below is what I have tried with no success (Novice to JS..)
var forename = retrieved['first_name']; // Didn't work
var forename = retrieved[1]; // Didn't work either
I have also tried 'for' loops, which haven't worked either (cannot locate the example i copied off..). I was at first trying to set the retrieved var to just (this.responseText) with no luck either. I literally just need a way that i can pull out parts of the array to stick into some jQuery like below:
$("#firstname").val = forename;
$("#lastname").val = surname;
(where 'forename' and 'surname' are the js variables from the array..)
Any help is appreciated as i am losing my mind!!
EDIT: When i was just using var retrieved = (this.responseText);, when i used typeof it said that the type was a string.. and var retrieved = new Array(this.responseText) comes back as an object.. I'm not sure how to access either.
var retrieved = JSON.parse(this.responseText);console.dir(retrieved)to look at the structure of the variable in your browser console, you may find out how the stuff inside it is structured and can access the field then.