Reputation: 25
Currently I'm send the following with JSON
{"John":[{"Coins":"600","First_name":"John"}]}
I doubt the line break should be there. I want to take the value of the coins in this case 600 and display it in a div.
function importCoins(str) {
if (str=="") {
document.getElementById("coins").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else { // code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status == 200){
alert(xmlhttp.response);
data = JSON.parse(xmlhttp.response);
receivedData(data);
}
}
function receivedData(data) {
document.write(data.Coins);
};
xmlhttp.open("GET","http://server/~name/folder/extractUser.php");
xmlhttp.responseType = "json";
xmlhttp.send();
}
importCoins();
Here is my PHP Code:
include("mysqlconnect.php");
$query = "SELECT Coins, First_name FROM users WHERE Id = 1";
$result = mysql_query($query) or die (mysql_error());
$data = array();
while($rows = mysql_fetch_array($result,MYSQL_ASSOC)){
$data[$rows['First_name']][] = $rows;
}
echo json_encode($data);
Upvotes: 0
Views: 1210
Reputation: 66354
and display it in a div
Assuming you have a <div id="my_target"></div>
in your HTML, setting text in it can be done as
var elm = document.getElementById('my_target'); // HTMLElement or null
elm.textContent = 'foo'; // set it's text to "foo"
This will only work after the Element exists. In other words, you need to wait for the page to finish loading or only initiate this code in a <script>
tag after the close tag of the element
Now, say you have an JavaScript Object var o = {bar: 'baz'};
, you can access it's properties like this
o['bar']; // "baz" (the value by accessing _key_ "bar" from _Object_ o
If you don't know the keys in an Object, you can do for..in
loop over them
var key;
for (key in o) {
console.log(key, o[key]); // logs "bar" "baz"
}
To wait for the current page to finish loading before invoking something, listen for the load event on the Window Object
window.addEventListener('load', function () {
// code to invoke after page has loaded
});
Finally, when using XMLHttpRequest to fetch JSON, you have inbuilt methods to parse it for you automatically, so you can get a JavaScript Object at the end.
var xhr = new XMLHttpRequest(),
method = 'GET',
url = "http://server/~name/folder/extractUser.php";
xhr.addEventListener('load', function (e) {
// code to invoke after receiving response
console.log(this.response); // let's log the object
});
xhr.open(method, url);
xhr.responseType = 'json'; // let the request know to expect JSON
xhr.send();
Putting it all together;
function getJSON(url, callback) {
var xhr = new XMLHttpRequest(),
method = 'GET';
xhr.addEventListener('load', function (e) {
callback(this.response);
});
xhr.open(method, url);
xhr.responseType = 'json';
xhr.send();
}
function displayCoins(obj) {
var elm = document.getElementById('my_target');
elm.textContent = obj["John"][0]["Coins"];
}
window.addEventListener('load', function () { // wait for page to load
// then invoke it
getJSON("http://server/~name/folder/extractUser.php", displayCoins);
});
Final note; always check your Console output when you encounter a problem with JavaScript or are debugging. This gives you much more information and usually will let you spot the problem, if not know which error message to google.
I'm struggling to adjust your final solution in order to fit in
var key; for (key in o) { console.log(key, o[key]); // logs "bar" "baz" }
Could you edit your completed solution to have unknown keys
I didn't include this because I didn't know the behaviour you wanted if there were many keys in your Object or just the one. I'll assume just one for this example;
Put the for..in
loop in the displayCoins
function
function displayCoins(obj) {
var elm = document.getElementById('my_target'),
key;
for (key in obj) {
elm.textContent = obj[key][0]["Coins"];
break; // stop after first key
}
}
Upvotes: 1
Reputation: 1547
You can pass it to a variable
and do:
var a = {"John":[{"Coins":"600","First_name":"John"}]};
console.log(a.John[0].Coins); //"600"
Upvotes: 0