I want to fetch the https://swapi.co/api/people/ all name and other detail but when I am using an axios call to get the data and I am getting undefined for all data but if want one name I am getting a CORS error in console.
let button = document.querySelector("#button");
let name = document.querySelector("#displayDetail");
function getDetail(){
var apiURL="https://swapi.co/api/people";
axios.get(apiURL).then(function(response){
showDetail(response.data);
});
}
function showDetail(data){
name.innerText=data.name;
}
button.addEventListener('click',getDetail);
The JSON data from https://swapi.co/api/people doesn’t have a name member. Instead it has a results member that is an array of objects, each of which has a name member.
So you need to loop through that data.results array to get each name:
function getDetail() {
var apiURL = "https://swapi.co/api/people";
axios.get(apiURL).then(function(response) {
showDetail(response.data);
});
}
function showDetail(data) {
for (i = 0; i < data.results.length; i++) {
console.log(data.results[i].name);
}
}
getDetail();
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
But note: That API endpoint paginates the results; so to get all the names, check data.next to get the URL for the next page, then make a new request with that URL to get the next set of results:
function getDetail(apiURL) {
axios.get(apiURL).then(function(response) {
showDetail(response.data);
});
}
function showDetail(data) {
for (i = 0; i < data.results.length; i++) {
names = names + data.results[i].name + "\n";
// name1.innerText = name1.innerText + "\n" + data.results[i].name;
}
if (data.next) {
getDetail(data.next);
} else {
console.log(names); // name1.innerText = names;
}
}
var names = "";
getDetail("https://swapi.co/api/people");
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
try with this
swapi.co/api/people/
change for
swapi.dev/api/people/
All resources support a search parameter that filters the set of resources returned. This allows you to make queries like:
https://swapi.co/api/people/?search=r2d2
To see the set of search fields for each resource, check out the individual resource documentation.
Related
I am trying to build a Calculator where you can Pick different Cryptocurrencies and build a Portfolio for Testing and Tracking. I choose Coingecko API v3 for this and use Fetch to do the API Calls. https://www.coingecko.com/en/api
The API Calls are working and I get JSON Data from the Server. I built a Function that is delivering the Top 100 Coins, putting them into a Datalist-Tag for Choosing from an Input:
function fetch_coinlist(url) {
fetch(url)
.then(function(response) {
if (response.status !== 200) {
alert("Can Not get Price Api! Status: " + response.status);
return;
}
response.json().then(function(data) {
document.getElementById("coinlist").innerHTML = "";
for (i = 0; i <= 99; i++) {
const toplist = document.createElement("option");
toplist.id = data[i].symbol;
toplist.innerHTML =
data[i].symbol.toUpperCase() + " - " + data[i].name;
document.getElementById("coinlisting").appendChild(toplist);
//console.log(data[i].id);
//console.log(data[i].name);
//console.log(data[i].symbol);
//console.log(data[i].image);
//console.log(data[i].current_price);
}
});
})
.catch(function(err) {
alert("Can Not get Price Api! Status: " + err);
});
}
<input list="coinlisting" id="coinlist" name="coinlist" class="curser-choose" />
<datalist id="coinlisting" placeholder="Choose Coin"></datalist>
This is working, I am using a For loop to go through the response. I try to Display the Price for a Coin if the User picked one Option from this Datalist and for further functionality I think it would be best that I could call an object like data.coinname.current_price so I can build a Function where i could pass a string to it and get the price for that coin.
However, right now I would have to use data[0].current_price for the current Price of the first item in the list. The items on the called List can Change over time, so I can not make a static assignment, I think I could do this each time I call the API but it would not benefit my target to have a function that I can feed with a name as a string to do the Price Call.
It is possible to get the Price in the same call as the list but I can not figure out how I would be able to do what I have in mind with that. On the site for the API are different calls listed, one of the first is the /coins/list call and it says "Use this to obtain all the coins’ id in order to make API calls" and gives a JSON object for each available coin like:
{
"id": "1inch",
"symbol": "1inch",
"name": "1inch"
}
Do I need to do this call first in order to achieve what I have in mind? But I'm unsure how that would help me get the solution I am looking for... I am struggling to find a solution for this and feel stuck, I feel like I don't understand it properly and it should be not as hard as I think it is right now :D If you have an idea of how to accomplish this please let me know!
You could do something like this. I kept the html simple.
fetch_coinlist: fetches a coin list. After fetching the coins list it converts the result to an object instead of a list. Each coin can be accessed using coins["<coin id>"].
show_coinlist does the visualisation
addEventListener catches when you select an item.
const gecko = "https://api.coingecko.com/api/v3/";
var coins = {};
// selector actions
const selector = document.querySelector('#coinlisting');
const info = document.querySelector('#info');
selector.addEventListener('change', event => {
info.innerHTML = "Selected item: " + selector.value + " : " + coins[selector.value].name;
});
function fetch_coinlist() {
fetch(gecko + "coins/list")
.then(function(response) {
if (response.status !== 200) {
alert("Can Not get List Api! Status: " + response.status);
return;
}
response.json().then(function(data) {
coins = {};
for (let i = 0, l = data.length; i < l; i++) {
let {id, ...info} = data[i];
coins[id] = info;
}
show_coinlist();
});
})
.catch(function(err) {
alert("Can Not get Price Api! Status: " + err);
});
}
function show_coinlist(){
for (let id in coins) {
let item = coins[id];
const toplist = document.createElement("option");
toplist.value = id;
toplist.innerHTML = item.symbol.toUpperCase() + " - " + item.name;
document.getElementById("coinlisting").appendChild(toplist);
}
}
fetch_coinlist();
<select id="coinlisting" placeholder="Choose Coin"></select>
<div id="info"></div>
Is it possible to add new data in API JSON response in AngularJS? I am consuming a REST API which returns country details, but I want to add more details to it.
After the API call, I'm getting this response:
There are few empty fields (red arrow). I need to fill it up using another API into each respective country, and also add new keys such as "id" etc if possible.
Is it possible to achieve this? and how?
Here is the code:
Api service.js (data which are going to be added)
$http.get("https://api.../getfile/rohit/fw18countries").success(function(data) {
teams = data.teams;
//console.log(data);
/* shuffle(teams); */
});
return {
GetTeams: function(){
return teams;
},
get: function(teamId) {
for (var i = 0; i < teams.length; i++) {
if (teams[i].id === parseInt(teamId)) {
return teams[i];
}
}
return null;
}
}
Controller.js
/* all teams data */
$scope.Allteams = wcAPI.GetTeams();
/* REST API call */
$http.get("http://api.../v1/competitions/467/fixtures")
.then(function(data) {
$scope.country = data;
console.log($scope.country);
});
So now, I need to update $scope.country (REST API data) using $scope.Allteams (my static data) with respective fields as mentioned above. Need to merge them respectively.
You can try this with the following code. Looping through the data arrays and findig the right one. Then adding all values to the object.
for(var i = 0; i< $scope.country.length; i++) {
//Find the right index from $scope.country
for(var j = 0; j< $scope.Allteams.length; j++) {
// TODO here you have to campare by right value
if($scope.country[i].id == $scope.Allteams[j].teamId) {
for(var key in $scope.AllTeams[j]) {
if(!$scope.Allteams[j].hasOwnProperty(key)) continue;
//Adds the value to the object
$scope.country[i][key] = $scope.Allteams[j][key];
}
break;
}
}
}
i had json file in that data is like this
[{"wingnum":0,"name":"vatsal chauhan","email":"chauhanvatsal81#yahoo.com","city":"bhavnagar","address":"asdf"},
{"wingnum":0,"name":"hardik","email":"hardikdave#gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"},
{"wingnum":0,"name":"kevin","email":"kevin#gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"},
{"wingnum":0,"name":"rohit","email":"rohit#gmail.com","city":"GANDHINAGAR","address":"Gandhinagar"}]
I want to search only name using fs.readfile or by any other option my code is shown below
exports.getdata = function(req,res,next){
console.log('reqobj',req.body.params.name);
fs.readFile('./server/api/Appartment/appartment.json', 'utf8',function read(err, data) {
/*obj = JSON.parse(data);
console.log(obj);*/
if (err) {
throw err;
}
else{
if (data === ""){
console.log('data does not exsist');
}
else{
console.log('exsist data getdata');
var arrayobject = JSON.parse(data);
console.log(arrayobject);
return res.status(200).json(data);
}
}
// res.end();
});
};
this code gives all data but i want to just get name according to parameter passed
like autocomplete
Once you've parsed the JSON and have the object in a variable, pass the object and the name to be searched in this function :
var searchname=function(x, somename){
for(var i = 0; i < x.length; i++) {
if (x[i]['name']==somename){
return i;
}
}
return -1; //This means no match found
}
For example, you can get the document containing the name you want by doing this in your code :
var index=searchname(arrayobject, req.body.params.name);
if (index!=-1){
console.log(json[index]);
// Or do something else with json[index]
}
Update: If you want to do a search within the object itself, and get all the names matching a criteria, here's how the function would change :
var searchname=function(x, somename){
var result=[];
for(var i = 0; i < x.length; i++) {
if (x[i]['name'].indexOf(somename)>-1){
result.push(x[i]['name']);
}
}
return result; //Array containing matched names. Returns empty array if no matches found.
}
console.log(searchname(arrayobject, req.body.params.name)); //To display the working of above for testing.
I'm looping over a set of URLs trying to get their HTML, but it only works for the last one in the list. The "NOT WRITING YET" console.log fires for everything in the urls array, as expected, but the console.logs after that only fire for the last one. They are all valid URLs and "res.on('error'....." returns nothing.
Any help is greatly appreciated!
for (var z in urls) {
var getURL = urls[z];
var copyURL = 'copies/'+getURL;
if (copyURL.indexOf('/') >= 0) {
var copyURLArr = copyURL.split('/');
} else {
var copyURLArr = [copyURL];
}
var copyFile = copyURLArr.pop();
var runningDirs = '';
for (var i in copyURLArr) {
if (runningDirs.length > 0) runningDirs += '/';
runningDirs += copyURLArr[i];
if (!require('fs').existsSync(runningDirs)) {
exec('mkdir '+runningDirs);
}
}
console.log('NOT WRITING YET: '+urlPrefix+getURL);
require('http').get(urlPrefix+getURL, function(res) {
console.log(urlPrefix+getURL);
res.on('data', function(data) {
console.log(copyURL);
require('fs').createWriteStream(copyURL, {flags:'a+'}).write(data);
});
});
}
In the line console.log(urlPrefix+getURL); the value will always be for the last url because when the callback is called the values of these variables will be from the last time they got assigned which is the last iteration in the loop.
instead make the request in a separate function like
function doRequest(url, copyURL) {
require('http').get(url, function(res) {
console.log(url);
res.on('data', function(data) {
console.log(copyURL);
require('fs').createWriteStream(copyURL, {flags:'a+'}).write(data);
});
});
}
and then call this function with doRequest(urlPrefix+getURL, copyURL) then check if the problem still exists
This is driving me crazy. I'm just trying to print out an array and it's not working. What am I missing? The results variable is returning "undefined" which much mean my for loop isn't working correctly. Everything else works properly, the console.log I have correctly displays the fields are added to the array.
// The list of accounts array.
var accountsArray = [];
function addAccount() {
// Take fields and put user data into varables.
var accountName = document.getElementById('accountName').value;
var accountBalance = document.getElementById('accountBalance').value;
var accountType = document.getElementById("accountType");
var accountTypeSelected = accountType.options[accountType.selectedIndex].text;
var accountCurrency = document.getElementById("accountCurrency");
var accountCurrencySelected = accountCurrency.options[accountCurrency.selectedIndex].text;
// Put these variables into the array.
accountsArray.push(accountName);
accountsArray.push(accountBalance);
accountsArray.push(accountTypeSelected);
accountsArray.push(accountCurrencySelected);
// Items added to the array, logged.
console.log('user added: ' + accountsArray);
}
function accountsListHtml() {
var results;
// Loop through the array
for (var i = 0; i < accountsArray.length; i++) {
results = accountsArray[i];
}
document.getElementById('accountsList').innerHTML = results;
}
Here's a link to all the files. It's an iOS web app using Framework7. Balance Pro
You are calling accountsListHtml() in body.onload. At that point accountsArray is empty.
I can't find any other possibility to call accountsListHtml() on that page you linked to.
Add one line inside function addAccount() and it will work:
function addAccount() {
/* vour code */
console.log('user added: ' + accountsArray);
accountsListHtml(); // add this line
}
Try changing results = accountsArray[i]; to results += accountsArray[i];.
Update
And initialize results with an empty string, for example :)
for (var i = 0; i < accountsArray.length; i++) {
results = accountsArray[i];
}
The statement in the for loop i.e. results = accountsArray[i]; overwrites the variable results evry loop run. You could change the statement to :
results += accountsArray[i].toString();
and initialise results to an empty string.
The following works for me: http://jsfiddle.net/95ztrmk3/13/
HTML:
<div id="accountsList"></div>
JS:
// The list of accounts array.
var accountsArray = [];
addAccount();
accountsListHtml();
function addAccount() {
// Take fields and put user data into varables.
var accountName = "John Doe";
var accountBalance = "500.00";
var accountTypeSelected = "Checking"
var accountCurrencySelected = "USD";
// Put these variables into the array.
accountsArray.push(accountName);
accountsArray.push(accountBalance);
accountsArray.push(accountTypeSelected);
accountsArray.push(accountCurrencySelected);
// Items added to the array, logged.
console.log('user added: ' + accountsArray);
}
function accountsListHtml() {
var results = [];
// Loop through the array
for (var i = 0; i < accountsArray.length; i++) {
results += accountsArray[i] + " ";
}
document.getElementById('accountsList').innerHTML = results;
console.log(results);
}
Assuming the input isn't malformed or otherwise weird. I made sure Javascript recognizes results is an empty array and not a string or something: var results = []