I have this code, but now I don't know how to delete from there, if I click on the X. I would like to find the id of the row, and then put it after the url. Now I don't know how to find the id.
const tBody = document.getElementById("tbody");
var url = "http://localhost:3000/users";
//
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {document.addEventListener('DOMContentLoaded', (event) => {
tBody.innerHTML="";
for(let i = 0; i < data.length; i++){
let newRow = document.createElement("tr");
newRow.innerHTML = `
<td>${data[i].id}</td>
<td>${data[i].title}</td>
<td>${data[i].author}</td>
<td> <button class="delete btn btn-primary">X</button> </td>`
tBody.appendChild(newRow);
}
});
});
//
const submitButton = document.getElementById("submit-button");
const titleInput = document.getElementById("inputTitle");
const authorInput = document.getElementById("inputAuthor");
submitButton.addEventListener("click", function(e){
e.preventDefault();
var newUser = {
title: titleInput.value,
author: authorInput.value,
};
var van = true;
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {
for(let i = 0; i < data.length; i++){
if (data[i].title===titleInput.value || data[i].author===authorInput.value) {
var z = i + 1;
var x = "/" + z;
var postUrl = url + x;
fetch(postUrl, {
method: 'PUT',
body: JSON.stringify(
{
title: titleInput.value,
author: authorInput.value,
id: data[i].id
}
),
headers: {
"Content-type": "application/json; charset=UTF-8"
}
});
van = false;
}
}
if(van===true) {
fetch(url, {
method: 'POST',
headers: {
"Content-type": "application/json; charset=UTF-8"
},
body: JSON.stringify(newUser)
}).then(response => response.json)
.then(json => console.log(json));
}
});
});
I tried this:
var tomb = [];
const removeTomb=(id)=>{
fetch(url, {method: "get"})
.then(result => {return result.json()})
.then(data => {
for(let i = 0; i < data.length; i++){
var b = {
id: data[i].id,
title: data[i].title,
author: data[i].author
}
tomb.push(b);
console.log(tomb);
}
let index=tomb.findIndex(tomb => tomb.id==id);
tomb.splice(index,1);
console.log(tomb);
});
};
and I put this onclick="removeTomb(${tomb[i].id})" before the X, but it does not work, because removeTomb is undefined.
Can you please explain me how it works? I want to learn from it! Thanks a lot!
Using const, function literal way wont work with HTML onclick="removeTomb(${tomb[i].id})". Try function removeTomb
Or assign the function to the window.
window.removeTomb = removeTomb
OR
var tomb = [];
function removeTomb(id) {
fetch(url, { method: "get" })
.then((result) => {
return result.json();
})
.then((data) => {
for (let i = 0; i < data.length; i++) {
var b = {
id: data[i].id,
title: data[i].title,
author: data[i].author,
};
tomb.push(b);
console.log(tomb);
}
let index = tomb.findIndex((tomb) => tomb.id == id);
tomb.splice(index, 1);
console.log(tomb);
});
};
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 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);
}
})
})
i tried it using session storage but i can't this my java script code i tried i need when i click a button return the id of printed data
function jobHome(){
const token = "rnxdQFzTU-YuzViH78aH";
//var id = 308;
const row = document.querySelectorAll("[id=brdr]")[0];
const container = document.getElementById("conte");
const jobtitle = document.getElementById("titleforjob");
const jbtime = document.getElementById("txs3");
const jbaddress = document.getElementById("txs2");
const jbtype = document.getElementById("txs1");
const title = document.getElementById("outputtitle");
const id = document.getElementById("outputid");
const show = document.getElementById("show");
$.ajax({
url: "https://successsroadv2.herokuapp.com/api/v1/Jobhome",
type: "GET",
dataType: "json",
headers: {
"Content-Type": "application/json",
Authorization: token
},
success: function (data) {
const myText = "";
const addressArray = [];
const titleArray = [];
const typeArray = [];
const idArray = [];
data.map((user) => {
addressArray.push(user.address);
titleArray.push(user.title);
typeArray.push(user.jtype);
idArray.push(user.id);
});
container.innerHTML = "";
for (let i = 0; i <= 3; i++) {
let clone = row.cloneNode(true);
container.appendChild(clone);
container.firstChild.innerHTML = "";
jobtitle.innerHTML = data[i].title;
jbtype.innerHTML= typeArray[i];
jbaddress.innerHTML= addressArray[i];
sessionStorage.setItem("jobid-"+i,idArray[i]);
//var ites =sessionStorage.getItem("jobid-"+i);
//console.log(ites);
//sessionStorage.setItem('jobid', JSON.stringify(idArray));
$('#bttn').click(function(){
const token = "rnxdQFzTU-YuzViH78aH";
const jbid = sessionStorage.getItem("jobid-"+i);
const hedtitle = document.getElementById("headertitle");
const jbtime = document.getElementById("txt3");
const jbaddress = document.getElementById("txt2");
const jbtype = document.getElementById("txt1");
const desc = document.getElementById("description");
$.ajax({
url: 'https://successsroadv2.herokuapp.com/api/v1/Jobhome/'+jbid+'',
type: "GET",
dataType: "json",
headers: {
"Content-Type": "application/json",
Authorization: token
},
success: function (data) {
hedtitle.innerHTML=data.title;
jbtype.innerHTML=data.jtype;
jbaddress.innerHTML=data.address;
jbtime.innerHTML=data.created_at;
//desc.innerHTML=data.desc;
return ;
},
error: function (error) {
console.log(`Error ${error}`);
}
});
});
}
},
error: function (error) {
console.log(`Error ${error}`);
}
});
}
$(document).ready(function () {
jobHome();
});
i need to get id of the clicked button in the div i had made an array of id the i get it from response body and make a for loop to repeat the div in HTML .. then i want to take the id for selected div when i click on the button of this div
I have a function that adds an item to a list and a function that deletes an item. When I add the item it displays correctly but the item cannot be deleted until I refresh the page. I'm using python 3, flask and javascript but I don't know why the delete function cannot be called on the newly created item. This is the relevant code:
index.html:
const checkboxes = document.querySelectorAll('.check-completed');
for (let i = 0; i < checkboxes.length; i++) {
const checkbox = checkboxes[i];
checkbox.onchange = function(e) {
console.log('click')
const newCompleted = e.target.checked;
const todoId = e.target.dataset['id'];
fetch('/todos/' + todoId + '/set-completed', {
method: 'POST',
body: JSON.stringify({
'completed': newCompleted
}),
headers: {
'Content-Type': 'application/json'
}
})
.then(function() {
document.getElementById('error').className = 'hidden';
})
.catch(function() {
document.getElementById('error').className = '';
})
}
}
const descInput = document.getElementById('description');
document.getElementById('form').onsubmit = function(e) {
e.preventDefault();
const desc = descInput.value;
descInput.value = '';
fetch('/todos/create', {
method: 'POST',
body: JSON.stringify({
'description': desc,
}),
headers: {
'Content-Type': 'application/json',
}
})
//.then(response => {
// return response.json()
// data = response.json()
//})
.then(response => response.json())
.then(jsonResponse => {
const li = document.createElement('li');
const checkbox = document.createElement('input');
checkbox.className = 'check-completed';
checkbox.type = 'checkbox';
checkbox.setAttribute('data-id', jsonResponse.id);
li.appendChild(checkbox);
const text = document.createTextNode(' ' + jsonResponse.description);
li.appendChild(text);
const deleteBtn = document.createElement('button');
deleteBtn.className = 'xbox';
deleteBtn.setAttribute('data-id', jsonResponse.id);
deleteBtn.innerHTML = '✗';
li.appendChild(deleteBtn);
document.getElementById('todos').appendChild(li);
document.getElementById('error').className = 'hidden';
})
.catch(function() {
console.error('Error occurred');
document.getElementById('error').className = '';
})
}
Delete code
const deletes = document.querySelectorAll('.xbox');
for (let i = 0; i < deletes.length; i++) {
const btn = deletes[i];
btn.onclick = function(e) {
console.log('click')
const todoId = e.target.dataset['id'];
fetch('/todos/' + todoId, {
method: 'DELETE'
})
.then(function() {
const item = e.target.parentElement;
item.remove();
})
}
}
app.py
#app.route('/todos/create', methods=['POST'])
def create_todo():
error = False
body = {}
# description = request.form.get('description', '')
# return render_template('index.html')
try:
description = request.get_json()['description']
todo = Todo(description=description)
#body['description'] = todo.description
db.session.add(todo)
db.session.commit()
body['id'] = todo.id
body['completed'] = todo.completed
body['description'] = todo.description
except:
error=True
db.session.rollback()
print(sys.exc_info())
finally:
db.session.close()
if error:
abort (400)
else:
return jsonify(body)
I got it. I had to name the update and delete functions and call them inside the add item function to attach the functions to the new css elements.
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) {
}
}