I am using the tool sheety ( https://sheety.co/ ) to put information into Google Sheets.
Unfortunately, I'm not very savvy with json and have pieced this together as much as I could.
The problem is that when the function is triggered, other columns are also changed. Does anyone have a solution why this is so and how I can prevent this?
I would be happy if someone could help me. If you have any questions, please do not hesitate to contact me.
var products = null;
// Called once the page has loaded
document.addEventListener('DOMContentLoaded', function(event) {
loadItems();
});
var projectUrl = 'XXX';
function loadItems() {
fetch(projectUrl + '/products')
.then((response) => response.json())
.then(json => {
this.products = json.products.sort((a, b) => {
return a.erledigt < b.erledigt;
console.log(json.products);
})
showAllItems();
console.log(json.products);
});
}
function drawItems(products) {
var template = Handlebars.compile(document.getElementById("products-template").innerHTML);
document.getElementById('products-container').innerHTML = template({
products: products
});
}
function showAllItems() {
drawItems(this.products);
}
function upvoteItems(id) {
let product = this.products.find(product => {
return product.id == id;
});
product.done = 1;
let headers = new Headers();
headers.set('content-type', 'application/json');
fetch(projectUrl + '/products/' + id, {
method: 'PUT',
body: JSON.stringify({ product: product }),
headers: headers
});
showAllItems();
}
Related
I am trying to build a movie web using tmdb api, JavaScript, css and html only. I tried to perform search query and show the results but the problem is that the results don't show up. When debugging, the status code received is 200 but when res.json() returns it just ends the fetch function and is not moving forward to the data. I will truly appreciate your help.
Thank you.
My url
const BASE_URL = "https://api.themoviedb.org/3/";
const API_KEY = "api_key=9b62c3eb4a6bc8acd4e26602f16fa744";
let SEARCH_URL = BASE_URL + "search/movie?" + API_KEY + "&sort_by=popularity.desc&query=";
My search function:
function searchMovie() {
let f = document.getElementById('search_movie');
f.addEventListener('submit', () => {
let user_input = search_input.value;
if (user_input && user_input.trim() != '') {
let query = SEARCH_URL + user_input;
console.log();
getMovies(query);
}
});
}
My fetch function:
function getMovies(my_api) {
main.innerHTML = '';
fetch(my_api, {
method: 'GET',
cache: "no-cache",
credentials: "same-origin",
headers: { "Content-Type": "application/json" }
}).then(res => res.json()).then(data => {
let arr = data.results;
if (arr && arr.length > 0) {
arr.forEach(movie => {
addMovie(movie);
});
}
else {
getMovies(MOVIE_URL, DEFAULT_PAGE);
console.log("Can't find results");
}
}).catch(err => {
console.log(err.message);
});
}
You were mostly there. The fetch call returns a promise, so you shouldn't set innerHTML to that. Instead, use the promise to wait for the fetch to complete, then update the dom with the result.
I also suggest separating the request and the dom manipulation as I've done below. It works...
const BASE_URL = "https://api.themoviedb.org/3/";
const API_KEY = "api_key=9b62c3eb4a6bc8acd4e26602f16fa744";
let SEARCH_URL = BASE_URL + "search/movie?" + API_KEY + "&sort_by=popularity.desc&query=";
function getMovies(my_api) {
return fetch(my_api, {
method: 'GET',
cache: "no-cache",
})
.then(res => res.json())
.catch(err => {
console.log(err.message);
});
}
function renderMovies(res) {
let ul = document.getElementById('results');
ul.innerHTML = '';
res.results.forEach(result => {
let li = document.createElement('li');
li.appendChild(document.createTextNode(result.title));
ul.appendChild(li);
});
}
let f = document.getElementById('search_movie');
f.addEventListener('click', () => {
let user_input = search_input.value;
if (user_input && user_input.trim() != '') {
let query = SEARCH_URL + user_input;
getMovies(query).then(renderMovies)
}
});
<input id="search_input"></input><br/>
<button id="search_movie">SEARCH</button><br/>
<ul id="results"></ul>
I am trying to get data from my front-end and store it in backend, however everytime I try to return it I receive `{ name: '' } in the terminal instead of the name I have inserted.
I have also tried to use Inspect Element to tell me where the error arises but it's not helping me as much.
Have attached my code below.
The code seems to cancel out the second "name" when I try to fetch data from localhost.
Any ideas. I have also attached screenshot for further clarity.
Thanks!
document.addEventListener('DOMContentLoaded', function () {
fetch('http://localhost:5001/getAll')
.then(response => response.json())
.then(data => loadHTMLTable(data['name']));
});
const addButton = document.querySelector('#add-name-button');
addButton.onclick = function () {
const nameInput = document.querySelector('#name-input');
constname = nameInput.value;
nameInput.value = '';
fetch('http://localhost:5001/insert',{
headers:{
'Content-type': 'application/json'
},
method: 'POST',
body: JSON.stringify({ name : name })
})
.then(response => response.json())
.then(data => insertRowIntoTable(data['data']));
}
function insertRowIntoTable(data){
}
function loadHTMLTable(data) {
const table = document.querySelector('table tbody');
console.log(data);
if (data.length === 0){
table.innerHTML = "<tr><td class = 'no-data' colspan = '5'> No Data </td></tr>";
}
}
constname = nameInput.value; should be const name = nameInput.value;
You should be using 'use strict' to avoid such errors(?) or a more advanced tools like linting etc.
I am the new guy in the JS and reactJS.
I want to get info from API to an array. I made API that show all the info from my DB.
It looks like this :
const [tempNew, setTempNew] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather')
.then(response => {
return response.json();
})
.then((jsonData) => {
let tmpArray = [];
for (var i = 0; i < jsonData.length; i++) {
tmpArray.push(jsonData.dayCelsius[i]) <---- here is the error
}
setTempNew(tmpArray);
})
}
Im want to collect all values from "dayCelsius" line into array.
What i need to change in this code ? Thank you :)
Can you provide more info about the error? But You can try using the map function like
const tmpArray = jsonData.map(r => r.dayCelsius);
You can use map function to return the dayCelsius value of each element and store them in the tmpArray.
let tmpArray = jsonData.map((el, i) => el.dayCelsius);
So, what I understand is that you are facing difficulty in just getting the dayCelsius value from the array of objects you fetch from your API.
It is difficult to make out what the problem is as more info about the error is required to see what is going wrong.
What I have done differently here is instead of the for-loop and jsonData.dayCelsius[i], I have used data.map((r,e) => r.dayCelsius).
const [temp, setTemp] = useState([]);
const getAllWeatherCelsius = () => {
fetch('http://localhost:5000/weather', {
method: "GET",
headers: {
Accept: "application/json",
"Content-Type": "application/json",
}
})
.then(response => {
return response.json();
})
.then((data) => {
const tempArray = data.map((r,e) => r.dayCelsius);
setTemp(tempArray);
})
.catch(err => console.log(err));
}
I hope it helps you, have a good day :)
I am trying to autofill city and state fields based on zip code input using sepomex API (for Mexico), on a site in corvid by wix, which is based on javascript but I think there is something wrong in the line json.response[0]["ciudad"].
$w.onReady(function () {
$w("#input1").onInput(() =>{
let zipcode = $w("#input1").value;
$w("#input2").value = "";
$w("#input3").value = "";
if (zipcode.length === 5) {
let apiUrl = "";
apiUrl = "https://api-sepomex.hckdrk.mx/query/info_cp/";
fetch(apiUrl + zipcode, {method: 'get'})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
else{
return Promise.reject("fetch was not successful")
}
})
.then((json) => {
console.log(json);
let response = json.response;
$w("#input10").value = json.response[0]["ciudad"];
$w("#input11").value = json.response[0]["estado"];
$w("#text148").collapse();
})
.catch(() =>{
$w("#text148").expand()
})
}
})
I can't display any data
There is the output on API
[
{
"error": false,
"code_error": 0,
"error_message": null,
"response": {
"cp": "44110",
"asentamiento": "Vallarta Poniente",
"tipo_asentamiento": "Fraccionamiento",
"municipio": "Guadalajara",
"estado": "Jalisco",
"ciudad": "Guadalajara",
"pais": "México"
}
}
]
change code inside second promise to.
.then((json) => {
let response = json[0].response;
$w("#input10").value = response.ciudad;
$w("#input11").value = response.estado;
$w("#text148").collapse();
})
now it should work
Solved
.then((json) =>{
let response = json[0].response;
$w("#input11").value = json[0].response["ciudad"];
$w("#input10").value = json[0].response["estado"];
$w("#text148").collapse();
})
Please, help me with this code. It runs very slow, about 2 minutes. I'm new to js and don't know how to improve it. I need to take data from multiple ajax requests and compare it. I tried to use for loops, $.map, but it works the same. What i'm doing wrong?
var user, post, image, comment;
$.when(
$.ajax({
url: "https://jsonplaceholder.typicode.com/posts",
success: function(postData) {
post = postData;
},
}),
$.ajax({
url: "https://jsonplaceholder.typicode.com/comments",
success: function(commentData) {
comment = commentData;
},
}),
$.ajax({
url: "https://jsonplaceholder.typicode.com/users",
success: function(userData) {
user = userData;
},
}),
$.ajax({
url: "https://jsonplaceholder.typicode.com/photos",
success: function(imageData) {
image = imageData;
},
}),
).then(function() {
$.each(post, function(index, postItem) {
$.each(comment, function(index, commentItem) {
$.each(user, function(index, userItem) {
$.each(image, function(index, imageItem) {
if (
postItem.id == commentItem.postId &&
postItem.id == imageItem.id &&
postItem.userId == userItem.id
) {
console.log(
"post title: " +
postItem.title +
" Post image: " +
imageItem.url +
" Author: " +
userItem.name +
" Comment: " +
commentItem.body
);
}
});
});
});
});
});
For the comments, users, and photos, transform the array of objects into a Map (or object), whose keys are the ids, and values are the values you want to extract from it later. Then loop over the posts, and from the ids in the post, look up the matching values on the Maps. If all 3 maps have a match, print the result.
Note that there's no need for a large dependency like jQuery just to make a network request and iterate over an array - built-in JS methods works just fine:
Promise.all(
['posts', 'comments', 'users', 'photos'].map(
path => fetch('https://jsonplaceholder.typicode.com/' + path).then(res => res.json())
)
).then(([posts, comments, users, images]) => {
const commentBodiesByPostId = new Map(
comments.map(comment => [comment.postId, comment.body])
);
const imageUrlsById = new Map(
images.map(image => [image.id, image.url])
);
const userNamesById = new Map(
users.map(user => [user.id, user.name])
);
for (const post of posts) {
const commentBody = commentBodiesByPostId.get(post.id);
const imageUrl = imageUrlsById.get(post.id);
const userName = userNamesById.get(post.userId);
if (commentBody && imageUrl && userName) {
console.log(`Post title: ${post.title}\nPost image:${imageUrl}\nAuthor:${userName}\nComment:${commentBody}`);
}
}
});
Using my Mapper util, you can optimise it very fast. see the sample.
You can find script here:
https://gist.github.com/deepakshrma/4b6a0a31b4582d6418ec4f76b7439781
var user, post, image, comment;
const results = Promise.all(
[
fetch("https://jsonplaceholder.typicode.com/posts").then( x => x.json()),
fetch("https://jsonplaceholder.typicode.com/comments").then( x => x.json()),
fetch("https://jsonplaceholder.typicode.com/users").then( x => x.json()),
fetch("https://jsonplaceholder.typicode.com/photos").then( x => x.json())
]
).then(function([posts, comments, users, images]) {
const postMapper = new Mapper(posts, "id")
const commentMapper = new Mapper(comments, "postId")
const userMapper = new Mapper(users, "id")
const imageMapper = new Mapper(images, "id")
console.log(posts, comments, users, images)
posts.forEach(post => {
const postM = postMapper.find(post.id)
const userM = userMapper.find(post.userId)
const imagM = imageMapper.find(post.id)
console.log(
postM,
userM,
imagM
)
})
});
class Mapper {
constructor(array, key) {
this.map = array.reduce((map, item) => {
const val = item[key];
if (!map[val]) {
map[val] = [];
}
map[val].push(item);
return map;
}, {});
}
find(key) {
return this.map[key] && this.map[key][Mapper.FIRST_INDEX]; //return blank array
}
findAll(key, returnUndefined) {
//return blank array
return this.map[key] ? this.map[key] : returnUndefined ? undefined : [];
}
}
Mapper.FIRST_INDEX = 0;