Javascript Fetch method [closed] - javascript

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 months ago.
Improve this question
Hello I'm new to JS and fetch api. I'm facing a problem that the following code perfectly works and show the datas from that api when I run that code with node and display in on the console. But when I try to show the datas from the api to the browser with JS DOM , it shows 403 error even though I include the authentication in the headers.
fetch('https://od-api.oxforddictionaries.com/api/v2/entries/en-gb/arrow'
, {
method: 'GET',
mode: 'no-cors',
headers: { app_id: "api_id", app_key: "api_key" },
})
.then((response) => response.json())
.then((data) => {
let noun = document.querySelector("#forNoun")
let verb = document.querySelector("#forVerb")
let nounEg = document.querySelector("#nounEg")
let verbEg = document.querySelector('#verbEg')
let searchbtn = document.getElementById("search")
let searchWord = document.getElementById("word")
let nounDef = document.createElement("p");
let verbDef = document.createElement("p")
let lexicalEntries = data.results[0].lexicalEntries;
let length = lexicalEntries.length
for (let i = 0; i < length; i++) {
console.log(lexicalEntries[i].lexicalCategory.text);
nounVerb.innerHTML = lexicalEntries[i].lexicalCategory.text
let senses = lexicalEntries[i].entries[0].senses;
for (let x = 0; x < senses.length; x++) {
if ("examples" && 'synonyms' in senses[x]) {
// console.log(senses[x].definitions[0])
noun.append(senses[x].definitions[0])
}
else if ('examples' in senses[x]) {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
else if ('synonyms' in senses[x]) {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
else {
noun.append(senses[x].definitions[0])
// console.log(senses[x].definitions[0])
}
}
}
});
`

Related

Create a dynamic function with JS [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 days ago.
Improve this question
I'm working in a project to create a knife in 3 parts and I want to create something like this. I don't really know if it's possible.
//selector
const imgBlade = document.querySelector('.piece__blade');
const imgPart = document.querySelector('.piece__part');
const imgMatter = document.querySelector('.piece__matter');
// here only 3 parts to create the knife but i have alot of more thant that
const shinyBladeImagePath = /img/products/shinyblade.png;
const centralePartImagePath = /img/products/centralePart.png;
const woodCentralePartPath = /img/products/woodCentralePart.png;
class piece {
constructor(name, info, path) {
this.name = name;
this.info = info;
this.path = path;
}
}
let shinyBlade = new piece('SB', 'Shiny Blade', shinyBladeImgPath);
let centralePart = new piece('CP', 'Centrale Part', centralePartImagePath);
let woodCentralePart = new piece('W01', 'Wood Centrale Part', woodCentralePartPath);
class knife {
constructor(blade, part, matter) {
this.blade = blade;
this.part = part;
this.matter = matter;
}
}
let firstKnife = new knife(shinyBlade, centralePart, woodCentralePartPath);
// here I want to create a function to create a dynamic "object" :
function showKnife(event) {
// Here I want to change path with on a click event
imgBlade.src = ;
imgPiece.src = ;
imgMatter.src = ;
}
shinyBladeTitle.addEventListener('click', () => {
showKnife.imgBlade.blade.path;
// here I want to click on a title option and change the imgBlade.src on my function
});
centralePartTitle.addEventListener('click', () => {
showKnife.imgPiece.piece.path;
// here I want to click on a title option and change the imgPiece.src on my function
});
woodTitle.addEventListener('click', () => {
showKnife.imgMatter.matter.path;
// here I want to click on a title option and change the imgPiece.src on my function
});
<div>
<img alt="Blade" src="/img/products/BLANK.png">
<img alt="Part" src="/img/products/BLANK.png">
<img alt="Piece" src="/img/products/BLANK.png">
</div>

i is not defined for loop in react project [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 3 years ago.
Improve this question
Does anyone have any idea why i is not defined in this loop? i cannot figure it out...
I'm trying to paginate through the pages of data received from an api and gather it all into one array and store it in state, but my for loop doesn't seem to be working because of the error: "i is not defined"
how else should i go about this???
gatherAllCharacters = () => {
fetch(`https://rickandmortyapi.com/api/character/`)
.then(res => res.json())
.then(data => {
let characters = data.results;
const totalPages = data.info.pages;
if (totalPages > 1) {
for (i = 2; i <= totalPages; i++) {
let page = i;
fetch(`https://rickandmortyapi.com/api/character/?page=${i}`)
.then(res => res.json())
.then(data => {
characters = characters.concat(data.results);
if (page === totalPages) {
this.setState({ allCharacters: characters });
}
});
}
} else {
console.log("none");
}
});
};
You can create a for loop like you have done above
for (i = 2; i <= totalPages; i++) {
//perform loop
}
However this generates a variable i in the global namespace and this is generally speaking a bad idea.
therefore you should initialise i before using it like so:
for (let i = 2; i <= totalPages; i++) {
//perform loop
}
Therefore ECMA decided to have a mode where this (and my other features that would cause undesirable side effects would instead throw an error).
see more here https://www.w3schools.com/js/js_strict.asp
As your app is in use-strict mode it will be throwing the error "i is not defined"
Remember to initialize any variable before using it!
Couple things you should know about let and var
var and let can change their value and const cannot change its value
var can be accessible anywhere in function but let and const can only be accessible inside the block where they are declared.
Because i is not defined. You need a var or let in front of i to define a new variable.
for(let i = 2; i <= totalPages; i++ )
- for (i = 2; i <= totalPages; i++) {
+ for (let i = 2; i <= totalPages; i++) {

How do i restructure following code? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I want to create an json structure with data which will get from an api call. I can generate the structure by using following code. But how can I restructure the code to remove nested call of function and loops.
var temp = {
applications: []
};
api.getApplications(conceptId)
.then((applications) => {
for (var i = 0; i < applications.length; i++) {
(function(indexOfAppArr) {
let applicationId = applications[indexOfAppArr].id;
temp.applications.push({
id: applicationId,
databases: []
});
api.getDbs(conceptId, applicationId)
.then(databases => {
for (var j = 0; j < databases.length; j++) {
(function(indexOfDatabasArr) {
let databaseid = databases[indexOfDatabasArr].id;
temp.applications[indexOfAppArr].databases.push({
id: databaseid,
tabels: []
});
api.
getSchema(conceptId,
applicationId, databaseid).
then(function(schemas) {
for (var k = 0; k < schemas.length; k++) {
(function(indexofschemaarr) {
let schemaid = schemas[indexofschemaarr].id;
api.getTable(conceptId, schemaid)
.then(function(tables) {
console.log(tables);
})
})(k)
}
})
})(j)
}
})
})(i)
}
})
Here is the JSON structure which i want to create.
{
applications:[{
id:'',
databases:[{
id:'',
tabels:[
{
id:'',
columnId:''
}
]
}]
}]
};
If you read a little you'll actually learn how to do it. I personally haven't had the need to learn it yet but it sounded interesting, here is an excellent website that I found for you:
https://javascript.info/promise-chaining
it explains there how to "restructure" the code you are asking by putting it in less words:
loadScript("/article/promise-chaining/one.js").then(function(script1) {
loadScript("/article/promise-chaining/two.js").then(function(script2) {
loadScript("/article/promise-chaining/three.js").then(function(script3) {
// this function has access to variables script1, script2 and script3
one();
two();
three();
});
});
});
I'm sure it only takes less than 30 mts of reading. Best of luck!

JavaScript seemingly unable to access object property [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Improve this question
So I have this object, Looks like this:
I am trying to access the when_is_meeting property. I dont have any issue accessing any other property in this object. But if I try to access when_is_meeting I get an undefined as seen above next to "WHEN IS IT"
This is what the code looks like....
var listOfObjects = [];
for (var modelData in responseData) {
listOfObjects.push(service.create(name, responseData[modelData]));
console.log('RESP', response.data.content[modelData]);
console.log('WHEN IS IT!!!',response.data.content[modelData].when_is_meeting);
}
Does anyone know what the heck is going on here? Did I spell something wrong? I've been over it 50 times. Must be something simple im overlooking.
----------------EDIT------HERE IS THE WHOLE SERVICE----------------------
service.fetch = function (name, id, options) {
options = options || {};
const ModelClass = service.models[name];
const baseUrl = ModelClass.getUrl(service.getBaseUrl(ModelClass), ModelClass.getModelName());
let url;
let paged = false;
let pageList = false;
if (id) {
if (id instanceof models.BaseModel) {
const BaseModelModelName = id.getModelName();
let baseModelWithId = ModelClass.getUrl(service.getBaseUrl(), BaseModelModelName);
url = [baseModelWithId, id.getId(), ModelClass.getModelName(), ''].join('/');
pageList = true;
} else {
url = [baseUrl, id].join('/');
}
} else {
pageList = true;
url = [baseUrl, ''].join('/');
}
if (options.path) {
url = url + options.path;
delete options.path;
}
if (typeof options.paged === 'object') {
let currentPage = options.paged.page;
let pageSize = options.paged.page_size || 20;
paged = options.paged;
options.page = currentPage;
options.size = pageSize;
if (options.paged.sort) {
let sortParam = options.paged.sort;
options.sort = sortParam.param+','+sortParam.order;
}
delete options.paged;
}
return AuthRequestsService.load.then(function () {
return $http({
method: 'GET',
url: url,
headers: {
'Authorization': AuthRequestsService.getAuthorizationHeader(),
},
params: options,
json: true
});
}).then(function (response) {
console.log('RESPONSE',response);
for (let i = 0; i < response.data.content.length; i++){
if (response.data.content[i].activity_history_type == 3){
let builder = JSON.parse(response.data.content[i].relations);
let secondaryUrl = AppSettings.apiUrl + ['/advisor/meetings', builder.meeting].join('/');
$http({
url: secondaryUrl,
headers: {
'Authorization': AuthRequestsService.getAuthorizationHeader(),
},
method:'GET',
json:true,
}).then(function(res){
response.data.content[i].when_is_meeting = res.data.meeting_date;
console.log('WHEN IS',response.data.content[i].when_is_meeting); // <-- this works
})
}
}
if (!pageList) {
return service.create(name, response.data);
} else {
let responseData = response.data;
if (paged) {
responseData = response.data.content;
}
var listOfObjects = [];
for (var modelData in responseData) {
listOfObjects.push(service.create(name, responseData[modelData]));
console.log('RESP', response.data.content[modelData]);
listOfObjects[modelData].when_is_meeting = response.data.content[modelData].when_is_meeting;
listOfObjects[modelData].whatever = 44;
console.log('response.data.content[modelData].when_is_meeting',response.data.content[modelData].when_is_meeting);
console.log('listOfObjects[modelData].when_is_meeting', listOfObjects[modelData].when_is_meeting);
console.log('listOfObjects[modelData].whatever', listOfObjects[modelData].whatever);
console.log('Keys', Object.keys(response.data.content[modelData]));
// console.log('PRE IF', response.data.content[modelData].when_is_meeting);
// listOfObjects[modelData].when_is_meeting = response.data.content[modelData].when_is_meeting;
// console.log('IFFFFFFFFFFFFFFFFFFFFF', listOfObjects[modelData].when_is_meeting);
// console.log('IN FOR LOOP RESP', response.data.content[modelData].when_is_meeting);
// console.log('listOfObjects[modelData] PART 2', listOfObjects[modelData]);
function testForKey() {
if (typeof response.data.content[modelData].when_is_meeting !== "undefined") {
// when_is_meeting now exists! Do stuff with it here.
console.log("We now have the key:", response.data.content[modelData].when_is_meeting)
}
else {
// when_is_meeting is still missing. Try again in 200ms.
window.setTimeout(testForKey, 200);
console.log('TTTIIMMMEEEEOOOUUUTTT');
}
}
testForKey();
}
if (paged) {
console.log('#########################', listOfObjects);
return {
objects: listOfObjects,
totalPages: response.data.totalPages,
currentPage: response.data.number,
isMore: (!response.data.last),
totalElements: response.data.totalElements
};
} else {
return listOfObjects;
}
}
});
};
This problem occurs because when you expand the toggle to view an object the console show what it has now, not what it had at the time it was logged.
This is explained well here: http://felix-kling.de/blog/2011/08/18/inspecting-variables-in-javascript-consoles/
This scenario is not uncommon when you are working with Ajax. You are trying to access the result before everything has completed; ie, something else in your code is working on your response.data and adding in the missing key after your console.log statements.
This is confirmed by the logging statement suggested in the comments above by #Steven. Object.keys(response.data.content[modelData])) will show the keys available at the time the log statement is made and hence does not have the same problem as just logging the object itself to the console. The results from that confirm when_is_meeting is indeed missing at log-time.
To fix this properly, we need to see more of your code so we can work out why you are trying to access your result before other things finish using it.
Or you can do a crude workaround using timeouts to test the response.data.content[modelData] for the availability of when_is_meeting and only access it when it exists, like the example below. But this is not really recommended - much better to figure out where the problem lies in your response handling.
var listOfObjects = [];
for (var modelData in responseData) {
listOfObjects.push(service.create(name, responseData[modelData]));
// testForKey looks for the required key 'when_is_meeting' and if it does not
// exist it starts a timeout to test for it again in the future.
function testForKey() {
if (typeof response.data.content[modelData].when_is_meeting !== "undefined") {
// when_is_meeting now exists! Do stuff with it here.
console.log("We now have the key:", response.data.content[modelData].when_is_meeting)
}
else {
// when_is_meeting is still missing. Try again in 200ms.
window.setTimeout(testForKey, 200);
}
}
testForKey();
}
(I've not tested this code - it might have syntax errors)
Update - a fix for your supplied code
Your supplied code shows that as predicted the when_is_meeting key is being added to your result in a separate Ajax call. This call complete asynchronously and as such its result is not available to your log statements below it. This fragment shows one approach for fixing it. As before, I have not syntax-checked this code.
return AuthRequestsService.load.then(function () {
return $http({
method: 'GET',
url: url,
headers: {
'Authorization': AuthRequestsService.getAuthorizationHeader(),
},
params: options,
json: true
});
}).then(function (response) {
console.log('RESPONSE',response);
for (let i = 0; i < response.data.content.length; i++){
if (response.data.content[i].activity_history_type == 3){
let builder = JSON.parse(response.data.content[i].relations);
let secondaryUrl = AppSettings.apiUrl + ['/advisor/meetings', builder.meeting].join('/');
// Store the result of this $http call as a promise.
response.data.content[i].when_is_meeting_promise = $http({
url: secondaryUrl,
headers: {
'Authorization': AuthRequestsService.getAuthorizationHeader(),
},
method:'GET',
json:true,
})
// Remove your .then handler from here. It will be dealt with below.
//.then(function(res){
// response.data.content[i].when_is_meeting = res.data.meeting_date;
// console.log('WHEN IS',response.data.content[i].when_is_meeting); // <-- this works
//})
}
}
if (!pageList) {
return service.create(name, response.data);
} else {
let responseData = response.data;
if (paged) {
responseData = response.data.content;
}
var listOfObjects = [];
for (var modelData in responseData) {
// OK, now access the promise you stored above. This means you'll be sure you'll
// have the when_is_meeting key.
responseData[modelData].when_is_meeting_promise.then(function(when_is_meeting_result) {
// Now you can copy the neeting date into your responseData object.
responseData[modelData].when_is_meeting = when_is_meeting_result.data.meeting_date;
// Carry on....
listOfObjects.push(service.create(name, responseData[modelData]));
console.log('RESP', response.data.content[modelData]);
// This should now work...
console.log('response.data.content[modelData].when_is_meeting',response.data.content[modelData].when_is_meeting);
});
}
}
});

Bug on line 52 of my javascript code and i can't figure it out [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 8 years ago.
Improve this question
I'm using the below javascript code in my appery.io app. I keep getting an error which states the following:
6/25/2014 9:37:35 PM: Script All_Users_Data: TypeError: Cannot read property '_id' of undefined ( # 52 : 33 ) -> if (all_photo[i].the_user._id == id) {
Please help me identify the bug. I'm attempting to pull data from 3 collections, sync them up by _id from a 'users' collection and then output user profile type information.
var all_users = eval(DatabaseUser.query('52895ecce4b056c5e94f34f9'));
var all_profiles = eval(Collection.query('52895ecce4b056c5e94f34f9', 'profile'));
var all_status = eval(Collection.query('52895ecce4b056c5e94f34f9', 'Status'));
var all_photo = eval(Collection.query('52895ecce4b056c5e94f34f9', 'photo'));
// loop on all users
for (var i=0;i<all_users.length;i++)
{
// call function to search for user profile and then add first name to current user item
getProfile(all_users[i]._id, all_users[i]);
// call function to search for user status and then add last status to current user item
getstatus(all_users[i]._id, all_users[i]);
getphoto(all_users[i]._id, all_users[i]);
}
// function get user item and user id and find user profile by its id and update it
function getProfile(id,curUser)
{
var found = false;
for (var i = 0; i < all_profiles.length; i++) {
// if cur user id = profile id assign profile name to the user
if (all_profiles[i].the_user._id == id)
{
curUser.firstName = all_profiles[i].firstName;
curUser.university = all_profiles[i].university ;
found = true;
}
}
if (!found)
{
curUser.f_name = "";
}
}
// function get user item and user id and find user status by its id and update it
function getstatus(id, curUser) {
var found = false;
for (var i = 0; i < all_status.length; i++) {
if (all_status[i].the_user._id == id) {
curUser.status = all_status[i].status;
found = true;
}
}
if (!found) {
curUser.status = "";
}
}
function getphoto(id, curUser) {
var found = false;
for (var i = 0; i < all_photo.length; i++) {
if (all_photo[i].the_user._id == id) {
curUser.photo = all_photo[i].photo;
found = true;
}
}
if (!found) {
curUser.photo = "";
}
}
// return full user data updated wih status and first name
response.success(JSON.stringify(all_users), "application/json");
It means this is undefined:
all_photo[i].the_user
So as it is undefined, it most definitely doesn't have the property _id, as undefined objects have no properties, because they are undefined.
Does that define the source of the problem?
--
Use your browser console - it helps:
console.log(all_photo);
Then you can check out what is happening with that object and what properties it does have after you eval it.

Categories

Resources