Using Javascript. I'm trying to loop through an array encoded with JSON. Here is a sample of the array:
{"test1":"some info","test2":"more info","test3":"more stuff"}
Inside each loop I am checking to see if a DIV id exists with the name of the keys.
<div id="test1"></div>
<div id="test2"></div>
<div id="test3"></div>
I'm using a for() loop, but I can't get it to work. If I remove the for() loop it works just fine if I search for only 1 DIV id.
for(var key in responseText)
Here is the script. Does anyone know how I can loop through the array from responseText using the array keys as the names of the DIV id's?
<script>
function loadInfo() {
var req = new Request({
method: 'get',
url: 'getinfo.php,
noCache: true,
onRequest: function() {
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', 'Loading');
}
}
},
onComplete: function(responseText, responseHtml) {
if (JSON.decode(responseText) != null) {
var data = JSON.decode(responseText);
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', data[key]);
}
}
}
},
onFailure: function() {
for (var key in responseText) {
if (document.getElementById(key)) {
$(key).set('html', '-');
}
}
}
}).send();
}
window.addEvent('domready', function() {
loadInfo();
});
</script>
You have to decode the JSON before you iterate over the keys. So, where you say:
for(var key in responseText) {
replace that with:
for(var key in data) {
assuming
var data = JSON.decode(responseText);
Also, some of your callback functions don't specify responseText as a parameter. If you want to access this for each callback, you have to explicitly include responseText as a parameter. Example:
onRequest: function(){
should be:
onRequest: function(responseText){
I think the problem is that you're using the wrong variable name.
var data = JSON.decode(responseText);
for(var key in responseText) {
Should read
var data = JSON.decode(responseText);
for(var key in data) {
Note that instead of responseText after in, it reads data.
Are you sure you don't want JSON.parse? This would parse the JSON response into a javascript object that you can use the for/in against.
var data = JSON.parse(responseText);
Also, you're missing a closing quotation mark after the url:
url:'getinfo.php', // Closed the quote
Related
First time question, hoping for some advice:
Code on webpage:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response);
}
});
});
});
};
</script>
</form>
This returns a string that I would like to work with that looks like this:
Answer:
[{"id":"1","answer":"Pull logging","question_id":"5","feature_id":"1","answer_id":"9"}]
Ideally what I would like to do is only select the 'value' to the maxmail_answer 'key' (hopefully those are the right terms?) to the webpage instead. Right now there is only one value but there will be more in the future so something that could parse this string for a specific key and only output those values.
Visually I would see:
Answer: Pull logging ( and then another Answer: for each value I pull out )
First time ever using this site and these languages so total noob and would appreciate some guidance.
Thanks!
You do not to stringify the JSON response, you can get the value of the key you want using the object notation . as follows:
function validateinbound() {
$('#inbound:input').each(function () {
var iv = $(this).val();
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
//var response = JSON.stringify(data); // no need for this line
$('#response').delay(3600).fadeIn(600);
// catch the answer here
// your result returns within an array so you need to catch the first index
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
});
});
});
};
Besides, ids are unique, you can only access a single element via id selector #, you do not need a .each
What you are receiving from your server is an array of objects in the JSON format. The sample that you have put has the length of "1" and therefore, if want to reach the "id" of the first array, it would be like this:
// var response = JSON.stringify(data); (// don't stringify it!
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+data[0].id);
You need here a loop to go through your array of results and display each result
success: function(data) {
var response = JSON.stringify(data);
$('#response').delay(3600).fadeIn(600);
$.each(response,function(index,value){//the each loop
$('#response').append("<p>Answer: </p>"+value.answer);//get the answer using . notation
});
}
Json.stringify() returns your javascript object as json data, but i think in your case your response is a json data which you need to manipulate. Json.parse() does this for you and you can access your answer as a property of the javascript object.
success: function(data) {
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+response[0].answer);
}
if your json data has multiple result and you need to work through all of them use a loop.
$.each(response,function(index, object){
var response = JSON.parse(data);
$('#response').delay(3600).fadeIn(600);
$('#response').append("<p>Answer: </p>"+object.answer);
});
First of all. Thank you to everyone who commented on this to help me get started in the right direction. I was able to get what I needed working!! Here is the solution:
<form id="inbound" action="javascript:validateinbound();">
<input type="submit" value="Go!" id="inbound">
<script>
function validateinbound() {
$('#controlpanel:input').each(function () {
var iv = $(this).val();
$('#response').html("");
$('#response').hide();
$('#mydiv').fadeIn(1200);
$('#mydiv').delay(1200).fadeOut(600);
$(function () {
$.ajax( {
url: 'validateinbound.php',
data: "variable="+iv,
dataType: 'json',
success: function(data) {
var newdata = JSON.stringify(data);
var response = JSON.parse(newdata);
$('#response').delay(3600).fadeIn(600);
$.each(response, function(array, object) {
$('#response').append("<p>Answer: </p>"+object.answer);
});
}
});
});
});
};
</script>
</form>
I needed to parse the data correctly. So I used JSON.stringify to get the data into a string that JSON.parse could use to manipulate the data. But function(index,object) wouldn't work because my output was not an index, but an array. So when changing to function(array,object) this allowed me to get my data just the way that I needed.
Again thanks to everyone for their help!
I'm trying to query a JSON file in my own server using $.getJSON and then cycling inside the objects. No problem so far, then i have an ID which is the name of the object i want to return, but can't seem to get it right:
var id = 301;
var url = "path/to/file.json";
$.getJSON( url, function( json ) {
var items = [];
items = json;
for (var i = 0; i < items.length; i++) {
var item = items[i];
console.log(item);
}
});
This prints the following in the console:
Now let's say i want return only the object == to id so then i can refer to it like item.banos, item.dorms etc.
My first approach was something like
console.log(json.Object.key('301'));
Which didn't work
Any help would be very much appreciated.
It seems like your response is wrapped in an array with one element.
You can access object properties dynamically via square brackets:
var id = 301;
var url = "path/to/file.json";
$.getJSON(url, function(json) {
console.log(json[0][id].banos);
});
As you have the name of the property in the object you want to retrieve you can use bracket notation. you can also simplify your code because of this:
var id = 301;
//$.getJSON("path/to/file.json", function(json) {
// response data from AJAX request:
var json = {
'301': {
banos: 2
},
'302': {
banos: 3
},
'303': {
banos: 4
},
'304': {
banos: 5
},
};
var item = json[id];
console.log(item);
//});
$.each(items,function(n,value){
if(n==301)
alert(value);
});
I have an Array storing objects each with another array inside. I'm using the Chrome Storage API to store these objects (for an extension). Writing data works fine, but I can't seem to extract the data I need:
Write to storage:
function writeToStorage(form) {
var formObjectsArr = [];
var data = [];
var formData;
$(':input', '#' + form)
.each(function() { data.push(this.value); })
.promise()
.done(function() {
var formData = new Form(data);
formObjectsArr.push(formData);
chromeStorage(formObjectsArr);
});
}
function chromeStorage(formObjectsArr) {
chrome.storage.sync.set({list:formObjectsArr}, function() {
console.log('Settings saved');
});
}
function Form(data) { this.data = data; }
Read from storage (not sure what to do here - the current function simply returns an object which contains an array which contains the object that contains the array I want to access):
function getFromStorage() {
chrome.storage.sync.get({list:[]}, function(test) {
console.log(data)
});
}
You can specify a string, array of strings, or a object dictionary to retrieve data stored in chrome extension's local or sync storage. Since you only want to retrieve the list keyed data, you can just use a string for the first argument of the sync.get method.
function getFromStorage() {
chrome.storage.sync.get("list", function(data) {
console.log(data);
});
}
On the jQuery AJAX success callback I want to loop over the results of the object. This is an example of how the response looks in Firebug.
[
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
]
How can I loop over the results so that I would have access to each of the elements?
I have tried something like below but this does not seem to be working.
jQuery.each(data, function(index, itemData) {
// itemData.TEST1
// itemData.TEST2
// itemData.TEST3
});
you can remove the outer loop and replace this with data.data:
$.each(data.data, function(k, v) {
/// do stuff
});
You were close:
$.each(data, function() {
$.each(this, function(k, v) {
/// do stuff
});
});
You have an array of objects/maps so the outer loop iterates over those. The inner loop iterates over the properties on each object element.
You can also use the getJSON function:
$.getJSON('/your/script.php', function(data) {
$.each(data, function(index) {
alert(data[index].TEST1);
alert(data[index].TEST2);
});
});
This is really just a rewording of ifesdjeen's answer, but I thought it might be helpful to people.
If you use Fire Fox, just open up a console (use F12 key) and try out this:
var a = [
{"TEST1":45,"TEST2":23,"TEST3":"DATA1"},
{"TEST1":46,"TEST2":24,"TEST3":"DATA2"},
{"TEST1":47,"TEST2":25,"TEST3":"DATA3"}
];
$.each (a, function (bb) {
console.log (bb);
console.log (a[bb]);
console.log (a[bb].TEST1);
});
hope it helps
For anyone else stuck with this, it's probably not working because the ajax call is interpreting your returned data as text - i.e. it's not yet a JSON object.
You can convert it to a JSON object by manually using the parseJSON command or simply adding the dataType: 'json' property to your ajax call. e.g.
jQuery.ajax({
type: 'POST',
url: '<?php echo admin_url('admin-ajax.php'); ?>',
data: data,
dataType: 'json', // ** ensure you add this line **
success: function(data) {
jQuery.each(data, function(index, item) {
//now you can access properties using dot notation
});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("some error");
}
});
Access the json array like you would any other array.
for(var i =0;i < itemData.length-1;i++)
{
var item = itemData[i];
alert(item.Test1 + item.Test2 + item.Test3);
}
This is what I came up with to easily view all data values:
var dataItems = "";
$.each(data, function (index, itemData) {
dataItems += index + ": " + itemData + "\n";
});
console.log(dataItems);
Try jQuery.map function, works pretty well with maps.
var mapArray = {
"lastName": "Last Name cannot be null!",
"email": "Email cannot be null!",
"firstName": "First Name cannot be null!"
};
$.map(mapArray, function(val, key) {
alert("Value is :" + val);
alert("key is :" + key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
if you don't want alert, that is u want html, then do this
...
$.each(data, function(index) {
$("#pr_result").append(data[index].dbcolumn);
});
...
NOTE: use "append" not "html" else the last result is what you will be seeing on your html view
then your html code should look like this
...
<div id="pr_result"></div>
...
You can also style (add class) the div in the jquery before it renders as html
I use .map for foreach. For example
success: function(data) {
let dataItems = JSON.parse(data)
dataItems = dataItems.map((item) => {
return $(`<article>
<h2>${item.post_title}</h2>
<p>${item.post_excerpt}</p>
</article>`)
})
},
If you are using the short method of JQuery ajax call function as shown below, the returned data needs to be interpreted as a json object for you to be able to loop through.
$.get('url', function(data, statusText, xheader){
// your code within the success callback
var data = $.parseJSON(data);
$.each(data, function(i){
console.log(data[i]);
})
})
I am partial to ES2015 arrow function for finding values in an array
const result = data.find(x=> x.TEST1 === '46');
Checkout Array.prototype.find() HERE
$each will work.. Another option is jQuery Ajax Callback for array result
function displayResultForLog(result) {
if (result.hasOwnProperty("d")) {
result = result.d
}
if (result !== undefined && result != null) {
if (result.hasOwnProperty('length')) {
if (result.length >= 1) {
for (i = 0; i < result.length; i++) {
var sentDate = result[i];
}
} else {
$(requiredTable).append('Length is 0');
}
} else {
$(requiredTable).append('Length is not available.');
}
} else {
$(requiredTable).append('Result is null.');
}
}
I'm having a little problem. I'm new in JS and I can't figure it out.
I'm trying to get a list of friends from Facebook. To do that I'm using the user posts and I want to show only the duplicates. My first answer is how to show all the friends from a loop and get only the duplicates (I want only one or two objects) and second is how to pass a var from a function to another function because I want to POST all the infos to a php file.
This is what I did:
function getInfo() {
FB.api(
'/me',
'GET',
{fields: 'first_name'},
function(response) {
friends();
var myname = response.first_name;
$.post(
"file.php",
{ myname:myname,friendsname:friendsname },
function(data) { $("body").append(data); }
);
}
With this function I'm getting my first name.
function friends() {
FB.api(
'/me/posts?fields=likes{id,name}',
{limit:50},
function(response) {
if (response.data) {
$.each(response.data,function(index, posts) {
var posturi = posts.likes;
$.each(posturi.data, function(useri, lista) {
var friendsname = lista.name;
});
});
}
}
);
}
And this is the list with my friends. If I check console.log(friendsname) it gives me all the friends with duplicates. But if I write an innerHTML in that $.each it returns me only 1 object. And how can I pass friendsname from friends() to getInfo() so I can post to that .php file?
That's because you're overwriting the value of innerHTML in every loop of $.each.
Try this:
var posturi = posts.likes;
var names = posturi.data.map(function(item) { return item.name; }).join(', ');
names will contain a comma separated list of names.