pull json data with ajax requests - javascript

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);
}

Related

How to return only part of JSON object from REST API with JQuery

So I've been trying to figure out a way to return only a specific key-value pair from a REST API call using JQuery. The initial call I'm going off of is:
jQuery.ajax({
type: "GET",
url: "https://BASEURL/api/project-type/list-all",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function ()
{
$('#projectTypeListLoading').text("Loading...");
},
success: function (data, status, jqXHR)
{
var trHTML = "";
$.each(data, function (i, item)
{
trHTML += '<tr><td>' + item.Name + '</td><td>' + item.Code + '</td><td>'
+ item.Order + '</td><td>' + item.IsActive + '</td><td>' + item.Id + '</td></tr>';
});
$('#projectTypesTable').append(trHTML);
$('#projectTypeListLoading').html("DONE");
},
error: function (jqXHR, status)
{
$('#projectTypeListLoading').html("Error loading list");
}
});
With this I can get a list of JSON Objects from my REST API like so:
[{"Name":"Project Type 2","Code":"2","Order":2,"IsActive":true,"Id":"c497e4e8-16b4-44e2-b6ac-a9a2c392d9d4"},{"Name":"Project Type 3","Code":"3","Order":3,"IsActive":true,"Id":"6da2a240-2327-4260-a6df-f4bec25535c2"}]
I then use these in my Ajax success portion and stick them in a table. Works perfectly. However, what I would like to have happen is to ONLY get say the Name key-value pair part of the JSON Object as the Response from my REST API. Like so:
[{"Name":"Project Type 2"},{"Name":"Project Type 3"]
And then in my Success function use:
success: function (data, status, jqXHR)
{
var trHTML = "";
$.each(data, function (i, item)
{
trHTML += '<tr><td>' + item.Name + '</td></tr>';
});
$('#projectTypesTable').append(trHTML);
$('#projectTypeListLoading').html("DONE");
},
I could achieve this result in two different ways. I could:
Change my REST API call to 'https://BASEURL/api/project-type/name'. And call this and have the API only return the name. I don't want to do this because I have 20 different urls which already return all, I will not be making a separate URL to access each key-value individually for each of these.
Get all like in my initial example then just ignore every key-value pair that isn't 'Name'. This would do what I want but the point is there will be many hundreds of these calls going on. Each of these calls would return the full JSON object then I'd cut that down; that's a lot of unnecessary chatter. I'd rather be able to specify which key-value pair I want to reduce server load.
Any advice on how to achieve this? Thanks.
There's no easy answer to this with REST endpoints. This is the exact problem that GraphQL, Falcor, OData and a number of other libraries were created to assist with.

Variable retrieve JSON

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}]}

Return Only Specific Values From Ajax JSON call

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>");
});
}

How to display the 2D array in Jquery in MVC ?

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));
});

Parse json object of multidimensional array

{
"prev": [
"demo/medium/Web081112_P002_medium.jpg",
"demo/medium/Web081112_P003_medium.jpg"
],
"curr": [
"demo/medium/Web081112_P004_medium.jpg",
"demo/medium/Web081112_P005_medium.jpg"
],
"next": [
"demo/medium/Web081112_P006_medium.jpg",
"demo/medium/Web081112_P007_medium.jpg"
]
}
This is the json I got :
<script>
$(document).ready(function(){
$.ajax({
type: "GET",
url: "scandir.php",
data: "page=5",
dataType: 'json',
success: function (data) {
$.each(data, function(i, data){
$('#img'+i).attr('src',data[1]);
});
}
});
});
</script>
I would like to do this: Assign <img id = "img1" src="demo/medium/Web081112_P002_medium.jpg"> and so on....
The collected data [1] only capture the values in column (3,5,7) . How to implement this? Thanks
since your are just setting the src attribute of the second data object here...
$('#img'+i).attr('src',data[1]);
you are getting the (3,7,5) only...
you have to use two $.each loops to get all the src..
try this
var k=1;
$.each(data, function(i, data1){
$.each(data1, function(j, data2){
$('#img' + k).attr('src', data2);
k++;
});
});
Try this if your array always has two elements:
$.each(data, function(i, data){
$('#img'+(2*i)).attr('src',data[0]);
$('#img'+(2*i + 1)).attr('src',data[1]);
});
If you have more than two, then you'll need an inner loop:
var idx = 0;
$.each(data, function(i, data) {
$.each(data[i], function(j, dataj) {
$('#img'+(idx)).attr('src',dataj[j]);
++idx;
});
});
That's not a multidimensional array, that is an object that has arrays as properties.
To loop through the arrays, you need another loop inside the loop. Use a separate counter to keep track of the image numbering.
var count = 1;
$.each(data, function(i, row){
$.each(row, function(j, item){
$('#img' + count).attr('src', item);
count++;
});
});
Note: There is no specific order to the properties in an object, so they may end up in different order depending on which browser the visitor is using.

Categories

Resources