get data from 2 connected JSON url in JavaScript - javascript

I've got a problem with JSON in JavaScipt. I've got 2 different JSON URL. One of them contains data about users and the second one about posts. And in posts JSON I've got a field userId.
I want to find a way to connect them somehow. I need to get users and their posts and then count how many posts every user wrote.
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users){
document.write("</br></br>"+ users[k].name +", " + users[k].username + ", " + users[k].email + "</br>" + "-------------------------------------------------------------------------------------" + "</br>");
for(k1 in posts){
if(posts[k1].userId===users[k].id){
document.write(posts[k1].body + "</br>");
}
}
}
};
userRequest.send();
};
postRequest.send();
but I think it doesn't look good. I want to get data from JSON to variable to use them later, in function for example.
Anyone help? I've never connected data from 2 JSON files and want to do it in a good way and getting good practice.

Use this instead
for(k in users){
for(k1 in posts){
if(posts[k1].userId===users[k].id){
if(!users[k].hasOwnProperty('posts')) {
users[k].posts = [];
}
users[k].posts.push(posts[k1].body);
}
}
}

if you could you jquery
$.when($.ajax({
url: "https://jsonplaceholder.typicode.com/users"
})).then(function(data, textStatus, jqXHR) {
$.each(data, function(index, value) {
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts?userId=" + value.id
}).then(function(data, textStatus, jqXHR) {
console.log("UserID:" + data[0].userId + " Nos Posts:" + data.length);
});
});
});
You can try above code and let me know if it solve your purpose

Steps you can use :
1. You can add a body property in to the objects in users array as per the id and userid match.
2. Later you can iterate the users array whenever you want to use.
DEMO
var postRequest = new XMLHttpRequest();
postRequest.open('GET', 'https://jsonplaceholder.typicode.com/posts');
postRequest.onload = function() {
var posts = JSON.parse(postRequest.responseText);
var userRequest = new XMLHttpRequest();
userRequest.open('GET', 'https://jsonplaceholder.typicode.com/users');
userRequest.onload = function (){
var users = JSON.parse(userRequest.responseText);
for(k in users) {
for(k1 in posts) {
if(posts[k1].userId===users[k].id){
users[k].body = posts[k1].body;
}
}
}
console.log("users", users);
};
userRequest.send();
};
postRequest.send();

Related

how to store array of objects using localstorage fron one file to other file

I am new to localstorage.I am trying to store json data in one file and retrieving the data in other file.Below is my json data which i have fetched from an url.I have tried storing feeds data using using localstorage now i am tring to fetch the data in other html file.But i am getting only the final object from the feeds.How can i get all the feed objects in other file.
{
"channel":{
"id":9,
"name":"my_house",
"description":"Netduino Plus connected to sensors around the house",
"latitude":"40.44",
"longitude":"-79.9965",
"field1":"Light",
"field2":"Outside Temperature",
"created_at":"2010-12-14T01:20:06Z",
"updated_at":"2017-02-13T09:09:31Z",
"last_entry_id":11664376
},
"feeds":[{
"created_at":"2017-02-13T09:07:16Z",
"entry_id":11664367,
"field1":"196",
"field2":"31.507430997876856"
},{
"created_at":"2017-02-13T09:07:31Z",
"entry_id":11664368,
"field1":"192",
"field2":"30.743099787685775"
},{
"created_at":"2017-02-13T09:07:46Z",
"entry_id":11664369,
"field1":"208",
"field2":"28.280254777070063"
}]}
One.html:-(here i am storing all the feeds data)
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are : \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
localStorage.setItem('Created_at', feed.created_at);
var create = localStorage.getItem('Created_at');
console.log(create);
localStorage.setItem('Entry_id', feed.entry_id);
var entry = localStorage.getItem('Entry_id');
console.log(entry);
localStorage.setItem('Field1', feed.field1);
var fd1 = localStorage.getItem('Field1');
console.log(fd1);
localStorage.setItem('Field2', feed.field2);
var fd2 = localStorage.getItem('Field2');
console.log(fd2);
});
other.html:(here i am trying to fetch the localstorage data)
<script>
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var create = localStorage.getItem('Created_at');
console.log(create);
document.writeln("<br>Created_at = "+create);
var entry = localStorage.getItem('Entry_id');
document.writeln("<br>Entry_id = "+entry);
var fd1 = localStorage.getItem('Field1');
document.writeln("<br>Field1 = "+fd1);
var fd2 = localStorage.getItem('Field2');
document.writeln("<br>Field2 = "+fd2);
}
</script>
Because you are over-riding the localStorage item in your for Loop.
The required for loop when simplified looks like:
json1.feeds.forEach(function(feed, i) {
localStorage.setItem('Created_at', feed.created_at); //Gets over-riden on every iteration
localStorage.setItem('Field1', feed.field1);});
That's why after the loop is completed. The Created_at field would only have the value of the most recently processed item in the array i.e. the last element. What you need to is create a corresponding array where each element would correspond to a feed item that you are reading from the API response.
Now, localStorage can simply store key value pairs. It doesn't have support for types like array. What you can do is something on these lines (Untested Code):
json1.feeds.forEach(function(feed, i) {
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
});
Yes, You will have to check if feedsArray key exists or not and set it as an empty array the first time. I have deliberately not put in the entire code as it is quite simple and should be good exercise for you.
So, once you are done and you want to read all the feeds from localStorage. Just get the feedsArray key and parse it and then iterate over it. Put simply, the basic idea is to have a JSON array of feeds and store it as a string with key feedsArray in localStorage.
The code snippet I have given above can get you started toward the solution I propose.
Relevant SO Post
The answer for the above issue is below.through which i got the solution.But not too sure if der is any wrong.
one.html:
$.ajax({
url : "https://api.thingspeak.com/channels/9/feeds.json?results=3",
dataType:"json",
cache: false,
error:function (xhr, ajaxOptions, thrownError){
debugger;
alert(xhr.statusText);
alert(thrownError);
},
success : function(json1) {
console.log(json1);
json1.feeds.forEach(function(feed, i) {
console.log("\n The deails of " + i + "th Object are :\nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2);
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
feedsArray.push(feed);
localStorage.setItem('feedsArray',JSON.stringify(feedsArray));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]')
}
});
other.html:
// Called on body's `onload` event
function init() {
// Retrieving the text input's value which was stored into localStorage
var feedsArray = JSON.parse(localStorage.getItem('feedsArray'));
for (var i = 0; i < localStorage.length;i++){
var savedArr =localStorage.getItem('feedsArray[i]');
//feedsArray.push(savedArr);
}
console.log(savedArr);
document.writeln("<br>FEEDS = "+savedArr);
}
</script

AngularJS and $http get JSON - data is not defined

Hi I am trying to retrieve some data from webservice using AngularJS $http get.
I have the following code snippet:
In the servicesjs:
.factory('BoothDesignatedCoordsService', ['$http', function ($http) {
var factory = {};
factory.getBoothDesignatedCoords = function (strBoothName, intFloorPlanID) {
var sendToWS;
var boothDesignatedCoords
var JSONObj = {
BoothName: strBoothName,
FloorPlanID: intFloorPlanID
};
sendToWS = JSON.stringify(JSONObj)
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords?objJSONRequest=' + sendToWS;
return $http.get(urlBase)
}
return factory;
}])
In the controllerjs:
var boothDesignatedCoords = BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3).success(function (response, data, status) {
console.log("successfully send booth name and floor plan id to ws");
console.log("data " + data + " , status : " + status);
console.log("data " + data);
boothDesignatedCoords = data;
for (var c = 0; c < boothDesignatedCoords.length; c += 2) {
}
The $http get is successful as I am able to print "successfully send booth name and floor plan id to ws" in the browser console log.
When I tried to print console.log("data " + data), it gives me some values of an integer array. That is exactly what I want. But in the controller I tried to assign data to the variable boothDesignatedCoords, the program does not run the for loop. Am I missing some code?
EDIT:
I tried to trace the code ( trace the variable called "data" in the controllerjs) and it says "data is not defined"
You appear to be confused about the methods available on the $http promise and their arguments. Try this
BoothDesignatedCoordsService.getBoothDesignatedCoords(strListShortListedBooth[i], 3)
.then(function(response) {
var data = response.data
var status = response.status
console.log('data', data) // note, no string concatenation
// and so on...
})
FYI, the success and error methods have been deprecated for some time and removed from v1.6.0 onwards. Don't use them.
I also highly recommend passing query parameters via the params config object
var urlBase = 'http://localhost:4951/wsIPS.asmx/fnGetBoothDesignatedCoords'
return $http.get(urlBase, {
params: { objJSONRequest: sendToWS }
})
This will ensure the key and value are correctly encoded.

What is the right way to send JSON to clients?

I want to develop an app for Pebble. This app is going to tell you how long it takes from one place you set in options to another one taking in account traffic jams and stuff.
To achieve this I need to make a page that will return JSON. Pebble retrieves information using code like that:
var cityName = 'London';
var URL = 'http://api.openweathermap.org/data/2.5/weather?q=' + cityName;
ajax(
{
url: URL,
type: 'json'
},
function(data) {
// Success!
console.log('Successfully fetched weather data!');
},
function(error) {
// Failure!
console.log('Failed fetching weather data: ' + error);
}
);
I created a small page with a js script that gets needed information from Yandex API:
var route;
ymaps.ready(init);
var myMap;
function init(){
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
var time = 0;
var home = getParameterByName("h");
var work = getParameterByName("w");
ymaps.route([home, work],{avoidTrafficJams: true}).then(
function (router) {
route=router;
time = ((route.getTime())/60).toFixed(2);
var info = new Object;
info["home"] = home;
info["work"] = work;
info["time"] = ~~time+"m"+~~((time%1)*60)+"s";
JSON.stringify(info);
},
function (error) {
alert('Возникла ошибка: ' + error.message);
}
);
}
As you can see I can get a JSON string in the end. But how do I send it to clients when a request with right parameters is made?
I ended up using phantomjs and executing this js script on my php page.

Foursquare hereNow from data.response.checkins?

I am trying to get the hereNow parameter from FourSquare using a checkins query on a specific user, unfrotunately I can't seem to get that parameter using checkins, I am seeing all other data regarding a venue except for the hereNow parameter.
Does anyone know how I can get that parameter using checkins? Otherwise, how can I incorporate venue objects and tie into my current code?
Here is my JavaScript to set hereNow as a variable:
var count;
getVenueStatus = function() {
var hereNowUrl = 'https://api.foursquare.com/v2/venues/VENUE_ID?&oauth_token=OAUTH_TOKEN&v=20140303';
$.getJSON(hereNowUrl, {format: "json"}, function(data) {
$(data.response.venue).each(function(index) {
$(this).each(function(index) {
var venue = this;
var hereNowCount = venue.hereNow.count;
count = hereNowCount;
console.log(count);
});
});
});
}
Here is my JavaScript to display the results on a map:
findFoodTrucks = function (param) {
getVenueStatus();
$.mobile.pageLoading();
var url = 'https://api.foursquare.com/v2/users/80507329/checkins?oauth_token=OAUTH_TOKEN&v=20140303';
var mapBounds = new google.maps.LatLngBounds();
if (param.userloc) mapBounds.extend(param.userloc);
$.getJSON(url, function(data) {
$(data.response.checkins).each(function(index) { // groups: nearby, trending
$(this.items).each(function(index) {
var foodtruck = this;
var foodtruckPosition = new google.maps.LatLng(foodtruck.venue.location.lat, foodtruck.venue.location.lng);
var foodtruckIcon = (count > 0) ? 'foodtruck_active.png' : 'foodtruck_inactive.png';
var foodtruckStreet = (foodtruck.venue.location.address) ? '<br>' + foodtruck.venue.location.address : '';
var foodtruckContent = '<strong>' + foodtruck.venue.name + '</strong>' + foodtruckStreet + '<br>';
mapBounds.extend(foodtruckPosition);
addFoodTruckMarker(foodtruckPosition, foodtruckIcon, foodtruckContent);
console.log(foodtruck);
});
if (param.zoomtotrucks) $('#map_canvas').gmap('getMap').fitBounds(mapBounds);
});
})
.error( function() {
loadFoodTrucks(param); //try again
})
.complete( function() {
$.mobile.pageLoading( true );
});
}
Thanks in advance!
The check-in response includes a compact venue, which is only sometimes guaranteed to have a hereNow field. To get the hereNow count, it's probably best to make a second venue detail API call.
PS: also noticed that you seemed to be passing an OAuth token and client ID/secret—in this case, you only need the OAuth token! Take a look at https://developer.foursquare.com/overview/auth for more info.

Populating an object with ajax in a loop

I need to pull data from a series of .csv files off the server. I am converting the csvs into arrays and I am trying to keep them all in an object. The ajax requests are all successful, but for some reason only the data from the last request ends up in the object. Here is my code:
var populate_chart_data = function(){
"use strict";
var genders = ["Boys","Girls"];
var charts = {
WHO: ["HCFA", "IWFA", "LFA", "WFA", "WFL"],
CDC: ["BMIAGE", "HCA", "IWFA", "LFA", "SFA", "WFA", "WFL", "WFS"]
};
var fileName, fileString;
var chart_data = {};
for (var i=0; i < genders.length; i++){
for (var item in charts){
if (charts.hasOwnProperty(item)){
for (var j=0; j<charts[item].length; j++) {
fileName = genders[i] + '_' + item + '_' + charts[item][j];
fileString = pathString + fileName + '.csv';
$.ajax(fileString, {
success: function(data) {
chart_data[fileName] = csvToArray(data);
},
error: function() {
console.log("Failed to retrieve csv");
},
timeout: 300000
});
}
}
}
}
return chart_data;
};
var chart_data = populate_chart_data();
The console in Firebug shows every ajax request successful, but when I step through the loops, my chart_data object is empty until the final loop. This is my first foray into ajax. Is it a timing issue?
There are two things you need to consider here:
The AJAX calls are asynchronous, this means you callback will only be called as soon as you receive the data. Meanwhile your loop keeps going and queueing new requests.
Since you're loop is going on, the value of filename will change before your callback is executed.
So you need to do two things:
Push the requests into an array and only return when the array completes
Create a closure so your filename doesn't change
.
var chart_data = [];
var requests = [];
for (var j=0; j<charts[item].length; j++) {
fileName = genders[i] + '_' + item + '_' + charts[item][j];
fileString = pathString + fileName + '.csv';
var onSuccess = (function(filenameinclosure){ // closure for your filename
return function(data){
chart_data[filenameinclosure] = csvToArray(data);
};
})(fileName);
requests.push( // saving requests
$.ajax(fileString, {
success: onSuccess,
error: function() {
console.log("Failed to retrieve csv");
},
timeout: 300000
})
);
}
$.when.apply(undefined, requests).done(function () {
// chart_data is filled up
});
I'm surprised that any data ends up in the object. The thing about ajax is that you can't depend on ever knowing when the request will complete (or if it even will complete). Therefore any work that depends on the retrieved data must be done in the ajax callbacks. You could so something like this:
var requests = [];
var chart_data = {};
/* snip */
requests.push($.ajax(fileString, {
/* snip */
$.when.apply(undefined, requests).done(function () {
//chart_data should be full
});

Categories