I have de next objet jSon:
{"prtg-version":"14.3.10.2422","treesize":3700,"":[{"objid":0,"probe":"","probe_raw":""}]}
I need the parametres to objid and prove and the next programm javascript:
$(document).ready(function()
{
/* call the php that has the php array which is json_encoded */
function act()
{
$.getJSON('https://10.213.8.25/api/table.json?columns=objid', function(data) {
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
$.each(data, function(key, val) {
$('ul').append('<li id="' + key + '">' + val.objid +' </li>');
});
});
});
}
setInterval(act, 1000);
});
if modifique my jSon all ok:
[{"objid":0,"probe":"","probe_raw":""}]
but the URL works with the before jSon and my programm javascrip and does not work can you help me to comment on the error?
Thank!
Given the following JSON:
{
"prtg-version":"14.3.10.2422",
"treesize":3700,
"":[{"objid":0,"probe":"","probe_raw":""}]
}
... I would first point out that it's highly unusual to have an empty string ("") as a JSON key. That being said, you can do that if you want. If you want to iterate over those values, though, you need to replace:
$.each(data, function(key, val) {
... with this:
$.each(data[""], function(key, val) {
I still have problems, I have armed the JSON object in PHP and call control and it works but by changing the URL address where you should get your information does not throw me anything you know if I make any changes?
$(document).ready(function()
{
/* call the php that has the php array which is json_encoded */
function act()
{
$.getJSON("https://10.213.8.25/api/table.json?&content=sensors&output=json&columns=objid&count=1&username=prtgadmin&password=SIEoperaciones01", function(data) {
//$.getJSON('DMS_PRTG_prueba.php', function(data) { ***OK***
/* data will hold the php array as a javascript object */
$.each(data, function(key, val) {
$('ul').append('<li id="' + key + '">' + val.objid +' </li>');
});
});
}
setInterval(act, 1000);
});
{"prtg-version":"14.3.10.2422","treesize":3188,"sensors":[{"objid":1001}]}
Related
I'm trying to pull in some json data using ajax. I am able to successfully pull data from the first 2 items but its the data under "placemark" that I really need. I need to be able to display this in a list much like an rssfeed. I'm not sure how to drill down deeper into the json to pull the data I need. any help greatly appreciated.
$.ajax({
type: 'GET',
url: rssAPI,
success: function(data){
console.log(data);
$.each(data, function(index, item) {
$.each(item, function(key, value) {
$('.listing').append(key + ': ' + value + '</br>');
});
});
}
});
here's what my json looks like
and this is my output
You need to either output, if the property value is a string, or iterate further (i.e. another loop) if it's an array, as is the case with the Placemark properties.
So:
$.each(data, function(index, item) {
$.each(item, function(key, value) {
if (typeof value != 'object')
$('.listing').append(key + ': ' + value + '</br>');
else
$.each(value, function(key, value) {
//these are your items under Placemark
});
});
});
Here placemark contains array of json objects. So you need to access it as below :
for(i=0; i<Document.Placemark; i++){
console.log(Document.Placemark[i].name);
console.log(Document.Placemark[i].description);
}
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 am getting following json from php
{"status":{"message":"success","undeleted":[],"code":200}}
{"status":{"message":"success","undeleted":[{"id":7844118,"error":"This Document already Published"}],"code":200}}
I just want to check 'undeleted' is empty or not in jquery.If not empty,I need to take every ids and its error message from 'undeleted'.I am not getting an idea how to do this .I will get only one at a time.
Thinking about something like this
var result = jQuery.parseJSON(data);
$.each(result.data, function(index, value) {
});
I have done something like this but not getting desired answer
var result = jQuery.parseJSON(data);
$.each(result.status, function(index, value) {
alert(value);
});
Here is how to do it:
http://jsfiddle.net/2zLby4r8/3/
var result = jQuery.parseJSON('{"status":{"message":"success","undeleted":[{"id":7844118,"error":"This Document already Published"},{"id":999999,"error":"New Errr"}],"code":200}}');
if (result.status.undeleted.length > 0) {
$.each(result.status.undeleted, function(index, value) {
alert("ID: " + value.id);
alert("Error: " + value.error);
});
} else {
alert("blank");
}
I'm having trouble with filtering the returned data from an Ajax JSON call. Right now, it returns:
{"results":[{"text":"RoboChat: What is it like to feel?","username":"RoboChat","createdAt":"2014-06-04T20:01:15.268Z","updatedAt":"2014-06-04T20:01:15.268Z","objectId":"wG2cs1OnVY"},
I'm trying to get it to return only the "text" object, like this:
"RoboChat:What is it like to feel?"
Here is my code:
function fetch () {
$.ajax({
url:"https://api.parse.com/1/classes/chats",
type : 'GET',
dataType : 'JSON',
data : JSON.stringify({
}),
success:function(data) {
$('.messages').append("<li>" + (JSON.stringify(data)) + "</li>")
}
});
};
I've tried passing a filter to JSON.stringify, but with no success, I'm not even sure if that's the way to approach filtering the data. Any help would be much appreciated.Thanks!
You can't really change what a request returns, but you can of course use the resulting value in any way you want. Since the response contains multiple objects with text properties, you have to iterate them and extract the text:
success: function(data) {
var results = data.results;
results.forEach(function (result) {
$('.messages').append("<li>" + result.text + "</li>");
});
}
The returned JSON has a results property which is an array, you can iterate through the array and read the text property of each element:
$.each(data.results, function(index, element) {
console.log(element.text);
});
For creating a li element for each array's element, you can use the $.map utility function:
var li = $.map(data.results, function(element) {
return '<li>' + element.text + '</li>';
});
$('.messages').append(li);
try for, the data has an array named results, from wich you have to select the first like following:
success: function(data) {
var results = JSON.parse(data).results;
results.forEach(function (result) {
$('.messages').append("<li>" + data.results[0].text + "</li>");
});
}
I am developing MVC application.
I am trying to pass the data from controller and trying to display using JQuery.
I create the array into Controller and pass it to Jquery using Json.
here is the array...
and here is the code of JQuery.
function getProductDetails(productCode, Index) {
$.ajax({
url: "/Product/getProductDetails/",
data: { Id: productCode },
dataType: "json",
success: function (result)
{
$.each(result.StockData, function (key, Value) {
alert(key + "+" + Value);
});
}
});
}
I have displayed the alert for the values...
it shows as below... Key shown perfectly but value shows as a object.
Try to stringify that object,
$.each(result.StockData, function (key, Value) {
alert(key + "+" + JSON.stringify(Value));
});
According to your new request try like,
$.each(result.StockData, function (key, Value) {
alert(key + "+" + (Value.Value));
});