Unable to fetch data from tmdb javaScript - javascript

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>

Related

400 "Bad Request" error when using Thunder Client (Postman) API

I am using the Thunder Client app for VS code to use an API to save the user's data. The API is okay but there is something wrong with my code because I keep getting a 400 "Bad Request" error when I try to send the data to the API. I think the problem might be an array in my code and that is not being sent correctly.
const form = document.querySelector('.form');
const refresh = document.querySelector('.refresh-button');
export const scores = [];
renderScores();
// event listener
form.addEventListener('submit', (e) => {
e.preventDefault();
saveScore();
renderScores();
});
refresh.addEventListener('click', (e) => {
e.preventDefault();
getScores();
renderScores();
});
function renderScores() {
const scoreList = document.querySelector('.result-list');
scoreList.innerHTML = '';
scores.forEach((score) => {
const li = document.createElement('li');
li.innerHTML = `${score.user} : ${score.score}`;
scoreList.appendChild(li);
});
}
async function getScores() {
const savedScores = 'https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/Zl4d7IVkemOTTVg2fUdz/scores/';
const recievedScores = await fetch(savedScores);
const api = await recievedScores.json();
const scores = api.result;
renderScores(scores);
}
async function saveScore() {
const user = document.querySelector('.fullname').value;
const score = document.querySelector('.thescore').value;
const newScore = {
user,
score,
};
scores.push(user, score);
await fetch('https://us-central1-js-capstone-backend.cloudfunctions.net/api/games/Zl4d7IVkemOTTVg2fUdz/scores/', {
method: 'POST',
body: JSON.stringify({
newScore
}),
headers: {
'Content-type': 'application/json; charset=UTF-8',
},
});
getScores();
}
Hey guys I changed my code a little and now I am not getting an error but when I refresh my page I lose all the data

how to call api recursively until nested stack keys are finished

here is my question how to call api recursively untill nested data stack keys are finished
here is my full explaination in image
i found this relatable code for recursion api call at this post recursive api call
function callFW() {
d3.json(url, async function(data) {
Tree["uid"] = data.request.uid
Tree["hid"] = data.firmware.meta_data.hid
Tree["size"] = data.firmware.meta_data.size
Tree["children"] = [];
await BuildTree(data.firmware.meta_data.included_files,Tree["children"]);
console.log(Tree)
})
}
async function BuildTree(included_files, fatherNode) {
if (included_files.length > 0) {
let promises = included_files.map( item => {
let url = endpoint + "file_object/" + item + "?summary=true";
return axios.get(url)
});
const results = await Promise.all(promises);
for(let response of results){
var node = {}
node["uid"] = response.data.request.uid
node["hid"] = response.data.file_object.meta_data.hid
node["size"] = response.data.file_object.meta_data.size
node["children"] = []
fatherNode.push(node)
await BuildTree(response.data.file_object.meta_data.included_files, node["children"]);
};
}
};
this is im using custom useRecurseFetch for getting post api result
but i have no idea how to change this code for recursive api call
import React from 'react';
import qs from 'qs';
import axios from 'axios';
const useRecurseFetch = query => {
const [status, setStatus] = React.useState('idle');
const [result, setResult] = React.useState([]);
const [findClass, setFindClass] = React.useState([]);
// console.log(passVariable);
var data;
data = qs.stringify({
query: `http://www.blabla{ ${query}/category}`,
});
// eslint-disable-next-line no-undef
var Grant = process.env.REACT_APP_GRANT;
// eslint-disable-next-line no-undef
var Client = process.env.REACT_APP_CLIENT;
// eslint-disable-next-line no-undef
var Key = process.env.REACT_APP_KEY;
// eslint-disable-next-line no-undef
var Auth = process.env.REACT_APP_AUTH;
// eslint-disable-next-line no-undef
var Query = process.env.REACT_APP_QUERY;
const queryCall = React.useCallback(
async token => {
if (!token) {
return;
} else {
setStatus('Loading');
var config = {
method: 'POST',
url: `${Query}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
Authorization:
token.data.token_type + ' ' + token.data.access_token,
},
data: data,
};
axios(config)
.then(response => {
setResult(response.data.results.bindings);
let originalResult = response.data.results.bindings
.filter(ek => ek.class !== undefined && ek)
.map(el => el.obj.value);
setFindClass(originalResult);
setStatus('success');
})
.catch(function (error) {
setStatus('error');
});
}
},
[data]
);
React.useEffect(() => {
const authInitiate = () => {
var data = qs.stringify({
grant_type: `${Grant}`,
client_id: `${Client}`,
client_secret: `${Key}`,
});
var config = {
method: 'POST',
url: `${Auth}`,
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
},
data: data,
};
axios(config)
.then(response => {
queryCall(response);
})
.catch(function (error) {
console.log(error);
});
};
authInitiate();
}, [queryCall]);
return [status, result, findClass];
};
export default useRecurseFetch;
please any one can help me out with this code, im unable to figure out whats going in this code
anyhelp is really saved my day and really so appreciatable
here i called useRecurseFetch custom function in app.js
const [loadingStatus, mainData, addDataToPostItemArray] = useRecurseFetch(
`<kk:cat>`
);
please any one can help me out please im stuck with this process of calling api

I am trying to make an AJAX fetch request and I keep getting an error "Uncaught SyntaxError: Unexpected token ')'"

I can't figure out where to put the curly brackets or parenthesis to make it work correctly. At first I thought the server was down or something but then I managed to console log the data. I kept uninstalling and reinstalling this visual studio code extension called "Bracket Colorizer" to try and solve the but I am all out of juice.
document.addEventListener('DOMContentLoaded', () => {
const title = document.createElement('h1');
title.innerText = 'Online Chatroom';
document.querySelector('body').appendChild(title);
// make AJAX call here....
fetch('https://curriculum-api.codesmith.io/messages')
.then(data => data.json())
.then(data => {
const main = document.querySelector('main')
for (let i = 0; i < data.length; i++) {
writeHTML(data[i], main)
// console.log(data);
});
};
};
Here is the rest of the code me and my tutor from wyzant worked on together if it helps.
document.querySelector('form').addEventListener('submit', sendMessage)
function writeHTML(message, htmlNode) {
let messageContainer = document.createElement('div')
let messageText = document.createElement('p')
messageText.innerHTML = message.message
messageContainer.appendChild(messageText)
let messageTime = document.createElement('span')
messageTime.classList.add('time')
messageTime.innerText = message.created_at
messageContainer.appendChild(messageTime)
linebreak = document.createElement("br");
messageContainer.appendChild(linebreak);
// // document.innerHTML(<br>)
let createdBy = document.createElement('span')
createdBy.classList.add('message_sender')
createdBy.innerText = message.created_by
messageContainer.appendChild(createdBy)
htmlNode.appendChild(messageContainer)
}
function sendMessage(event) {
event.preventDefault()
let newMessage = document.querySelector('textarea').value
let data = {
message: newMessage,
//figure out how to add another text box and insert that data here
created_by: "Matthew",
created_at: Date.now()
}
fetch('https://curriculum-api.codesmith.io/messages', {
method: 'POST',
body: JSON.stringify(data),
headers: {
'Content-Type': 'application/json'
}
}).then(function(response){
return response.json()
})
.then(function(response){
const main = document.querySelector('main')
writeHTML(response[0], main)
})
.catch(function(error){
console.error(error)
})
};
This parenthesis is misplaced:
// console.log(data);
}); <-- this one
};
// console.log(data);
}
}); <-- should be here
You had two parenthesis misplaced, you can check with the code below:
document.addEventListener('DOMContentLoaded', () => {
const title = document.createElement('h1');
title.innerText = 'Online Chatroom';
document.querySelector('body').appendChild(title);
// make AJAX call here....
fetch('https://curriculum-api.codesmith.io/messages')
.then(data => data.json())
.then(data => {
const main = document.querySelector('main')
for (let i = 0; i < data.length; i++) {
writeHTML(data[i], main)
// console.log(data);
}
})
})

Google Sheets - Insert via json

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

How to pass multiple arguments to one function?

I'm working on a project for school, and i'm trying to use 2 parameters in a function, but they are from 2 different functions. I have no clue how i can use them both.
What i'm trying to do is to actually use the code in showCityInfo in the function handleClickImg, but in order to do that i need the data 'city'
which is passed onto showCityInfo from the function getCityInfo, where the data is collected from my php.
So in short, i want to use the data 'city' and 'marker(=e.currentTarget)' in a function to do the following code i put in bold
{
const init = () => {
let radiobutton = document.querySelectorAll('.radio_button');
radiobutton.forEach(r => {
r.addEventListener("change", changeOpacity);
let $heart = document.querySelectorAll('.sidebar > svg');
$heart.forEach(h => {
h.addEventListener('click', changeColor);
})
document.documentElement.classList.add('has-js');
const $input = document.querySelector(`.world_form`);
console.log($input);
if ($input) {
$input.addEventListener(`change`, handleChangeFilter);
}
});
$markers = document.querySelectorAll('.world_map > img');
console.log($markers);
$markers.forEach(marker => {
marker.addEventListener('click', handleClickImg);
})
}
const handleChangeFilter = e => {
const alignment = e.target.value;
console.log(alignment);
const path = window.location.href.split(`?`)[0];
const qs = `?alignment=${alignment}`;
getCityInfo(`${path}${qs}`);
};
const getCityInfo = async url => {
console.log(url);
const response = await fetch(url, {
headers: new Headers({
Accept: 'application/json'
})
});
const city = await response.json();
console.log(city);
window.history.pushState({}, ``, url);
showCityInfo(city);
};
const showCityInfo = city => { **
const $parent = document.querySelector(`.contact_wrapper`);
$parent.innerHTML = ``;
$parent.innerHTML += `<p class="contact_info"><span>email:</span> Carvee${city.name}#hotmail.com</p>
<p class="contact_info"><span>tel:</span> ${city.tel} 476 03 51 07</p>` **
};
const handleClickImg = e => {
marker = e.currentTarget;
console.log(marker);
if (marker.id == city.city_code) {
}
}
In case you only have to compare a city and a marker at a time, I think what you should do is declare two global variables outside of the functions to store the city and marker data and be able to access and compare them anywhere.
//...
let city, marker;
const getCityInfo = async url => {
console.log(url);
const response = await fetch(url, {
headers: new Headers({
Accept: 'application/json'
})
});
city = await response.json();
console.log(city);
window.history.pushState({}, ``, url);
showCityInfo();
};
const showCityInfo = () => {
const $parent = document.querySelector(`.contact_wrapper`);
$parent.innerHTML = ``;
$parent.innerHTML += `<p class="contact_info"><span>email:</span> Carvee${city.name}#hotmail.com</p><p class="contact_info"><span>tel:</span> ${city.tel} 476 03 51 07</p>`
};
const handleClickImg = e => {
marker = e.currentTarget;
console.log(marker);
if (marker.id == city.city_code) {
}
}

Categories

Resources