How to render python dictionary values in Javascript Fetch API (forEach)? - javascript

I am trying to render python dictionary values inside a Javascript Fetch API. I tried various ways to do so such as serializing values and using dictionary keys to access the dictionary values. I got no error message but the values I rendered are all "undefined" on my webpage.
Python
def portfolio_position(request):
positions = Portfolio.objects.filter(owner=request.user, off_portfolio=False).order_by('-symbol').values()
return JsonResponse([position for position in positions], safe=False)
Javascript
function load_portfolio_position() {
fetch('/portfolio_position')
.then(response => response.json())
.then(positions => {
console.log(positions);
var table = document.getElementById("portfolio-table");
positions.forEach(position => {
var row = table.insertRow(1);
row.id = `row_${position.symbol}`;
var symbol = row.insertCell(0);
var price = row.insertCell(1);
var change = row.insertCell(2);
var average_cost = row.insertCell(3);
var position = row.insertCell(4);
var pnl = row.insertCell(5);
var pnl_percent = row.insertCell(6);
symbol.innerHTML = `${position.symbol}`;
price.innerHTML = `${position.price}`;
change.innerHTML = `${position.change}`;
var avc = parseFloat(position.cost).toFixed(3);
average_cost.innerHTML = `${avc}`;
position.innerHTML = `${position.position}`;
pnl.innerHTML = `${position.pnl}`;
pnl_percent.innerHTML = `${position.pnl_percent}`;
});
})
}
Appreciate your help!

Related

Filling HTML Table with Javascript - SLOW

I'm having trouble filling a HTML table with javascript efficiently.
For some background; I have a database with around 270k~ entries. I'm using the Javascript Fetch API to retrieve the rows of the SQL database from flask (i.e. my backend). The data transfer is fast - for example I can get the size of the database in less than a second, so that's not the bottleneck.
However, when I loop over the fetch results and try to fill a HTML table with even 50,000 entries, it takes over 15 seconds and the app locks up.
I have read this could be because I'm reading from the DOM, and that reading from native JS storage would be faster.
Would anyone have suggestions on how to solve this bottleneck?
My functions are below - I'm simply looping over the fetch promise and filling with the info.
async function getDB(){
let x;
console.log('Trying to get the entire database')
const res = await fetch('http://localhost:5000/getDB')
.then(function (response){
return response.json();
}).then(function (data) {
x = data
})
return x
};
function fillData(results){
// Dynamically filling the data...
results.then(
function(value) {
var table = document.getElementById("transactions-table");
let sortable = [];
for(var key in value){
// console.log(key + ": " + value[key]);
sortable.push([key, value[key]])
// console.log(key + )
}
sortable.sort(function(a, b){
return a[1] - b[1];
})
for(var key in value){
var row = table.insertRow(key);
var cell1 = row.insertCell(0); // <th>Id</th>
var cell2 = row.insertCell(1); // <th>Forename</th>
var cell3 = row.insertCell(2); // <th>Surname</th>
var cell4 = row.insertCell(3); // <th>Location</th>
var cell5 = row.insertCell(4); // <th>Amount</th>
cell1.innerHTML = value[key][0]
cell2.innerHTML = value[key][1] // Needs to be an index of the row tuple
cell3.innerHTML = value[key][2] // Needs to be an index of the row tuple
cell4.innerHTML = value[key][3] // Needs to be an index of the row tuple
cell5.innerHTML = value[key][4] // Needs to be an index of the row tuple
// row.style.backgroundColor = "red"
}
var row = table.insertRow(0);
var cell1 = row.insertCell(0)
var cell2 = row.insertCell(1)
var cell3 = row.insertCell(2)
var cell4 = row.insertCell(3)
var cell5 = row.insertCell(4)
cell1.innerHTML = "<b>ID</b>"
cell2.innerHTML = "<b>Forename</b>"
cell3.innerHTML = "<b>Surname</b>"
cell4.innerHTML = "<b>Location</b>"
cell5.innerHTML = "<b>Amount</b>"
},
function(error) {
console.log('Oh damn')
console.log(error)
}
)
}
No method I can think of so far.

javaScript JSON localstorage, user input, only saving first entry

I am busy doing an online boot camp, and only recently started learning JavaScript, I was also introduced to JSON in this task, the task I am currently busy with, must take user input and store it in local storage, and also display it on the webpage. The user should also be able to edit or delete data already saved (I haven't even gotten to that part yet), I am just trying to get the data to store.
I finally got the input to display, but it is not storing it to the localStorage. I have googled a lot and followed online tutorials.
Any help or advice will be greatly appreciated. I have included my JS file below.
let entry = document.getElementById("entry");
entry.addEventListener("click", displayDetails);
let row = 1;
function displayDetails() {
let title = document.getElementById("title").value;
let artist = document.getElementById("artist").value;
let album = document.getElementById("album").value;
let genre = document.getElementById("genre").value;
if (!title || !artist || !album || !genre) {
alert("Please fill all boxes");
return;
}
let display = document.getElementById("display");
let newRow = display.insertRow(row);
let cell1 = newRow.insertCell(0);
let cell2 = newRow.insertCell(1);
let cell3 = newRow.insertCell(2);
let cell4 = newRow.insertCell(3);
cell1.innerHTML = title;
cell2.innerHTML = artist;
cell3.innerHTML = album;
cell4.innerHTML = genre;
row++;
}
displayDetails = (ev) => {
ev.preventDefault(); //to stop the form submitting
let song = {
title: document.getElementById("title").value,
artist: document.getElementById("artist").value,
album: document.getElementById("album").value,
genre: document.getElementById("genre").value,
}
entry.push(entry);
document.querySelector("form").reset();
let pre = document.querySelector("#msg pre");
pre.textContent = '\n' + JSON.stringify(entry, '\t', 2);
localStorage.setItem("MySongList", JSON.stringify(entry));
}
document.addEventListener("DOMContentLoaded", () => {
});
Declare songList array outside function and push the song object into songList and then save it as string into localStorage as given in the below code snippet.
let entry = document.getElementById("entry");
entry.addEventListener("click", displayDetails);
let row = 1;
const songList = [];
function displayDetails() {
// your code......
const song = {
title: document.getElementById("title").value,
artist: document.getElementById("artist").value,
album: document.getElementById("album").value,
genre: document.getElementById("genre").value,
}
songList.push(song);
// your code......
localStorage.setItem("MySongList", JSON.stringify(songList));
}

Unable to dynamically add products to cart using Javascript

I am very new to Javascript and I'm building an ecommerce site, I am trying to add the image, name and price of an item and have it dynamically load in my cart. I can't seem to get the scripting right to get this to function properly, and my code is slowly becoming a mess of failed attempts, lol. Please help, here is the code.
var cart = [];
function products () {
var productTable = document.getElementById("productTable");
for (var i in cart) {
var row = productTable.itemRow(1);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
cell0.innerHTML = cart[i].image;
cell1.innerHTML = cart[i].name;
cell2.innerHTML = cart[i].price;
};
};
var addButton = document.getElementsByClassName("addToCart");
addButton.addEventListener('click', function(e) {
addToCart(itemImg, itemName, itemPrice) {
for (var i in cart) {
if (cart[i].name === itemName) {
return;
}
this.image = itemImg
this.name = itemName
this.price = itemPrice
};
var itemImg = $(this.parentElement).find("img").attr('src');
var itemName = $(this.parentElement).find("h3").text();
var itemPrice = $(this.parentElement).find(".price").text();
cart.push ({
itemImg,
itemName,
itemPrice,
});
};
<button class="addToCart">Add to cart</button>

How to read values from a Firebase Database and store them into an HTML table

I have a Firebase Database that stores two values distance and a timestamp. I'm able to read the distances, but un able to read to more than 1 timestamp at a time.
for (var i = 0; i <= 10; i++) {
ref.child("distance").child(i).once("value").then(function(snapshot) {
test = snapshot.val();
test1 = JSON.stringify(test).replaceAll(/[^a-zA-Z0-9.]/g, "");
myCreateFunction(test1, i+"");
});
ref.child("time").child(i).once("value").then(function(snapshot) {
time1 = snapshot.val();
console.log(time1);
myCreateFunc(time1["0"], i+"");
});
}
function myCreateFunction(test1, i) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell2.id = i;
cell1.innerHTML = test1;
}
function myCreateFunc(time1, i) {
document.getElementById(i).innerHTML = time1;
}
This is a picture of my database
This is the picture of the error that we get on our webpage
I think you are only sending your first element of the array to the HTML create table:
myCreateFunc(time1["0"], i+"");
instead of something like this:
myCreateFunc(time1, i+"");
Let me know if this solved your problem!

Using json array to populate html table

I am using local storage to save an object. I am having troubles than using this object to populate a table. Right now the object is showing up as an array in the third column. How can I use the json array to fill column 1, column 2 and column 3 with the value, key and image from the object.
$(document).on('click', '[data-toggle=add]', function() {
var latlng = $(this).data('latlng');
var address = $(this).data('address');
var image = $(this).data('image');
var key = $(this).data('id');
var testObject = {
'latlng' : latlng,
'address' : address,
'image' : image
};
localStorage.setItem(key, JSON.stringify(testObject));
updateTable();
});
function updateTable() {
var tbody = document.getElementById("output");
while(tbody.getElementsByTagName("tr").length > 0) {
tbody.deleteRow(0);
}
var row;
if(localStorage.length == 0) {
row = tbody.insertRow(i);
cell = row.insertCell(0);
cell.colSpan = "4";
cell.innerHTML = "Nothing to Show";
}
for(var i = 0; i < localStorage.length; ++i) {
row = tbody.insertRow(i);
cell = row.insertCell(0);
cell.innerHTML = i;
cell = row.insertCell(1);
cell.innerHTML = localStorage.key(i)
cell = row.insertCell(2);
cell.innerHTML = localStorage.getItem(localStorage.key(i));
cell = row.insertCell(3);
cell.innerHTML = '<button class="btn btn-danger btn-sm" onclick="deleteItem(\'' + localStorage.key(i) + '\');"><i class="fa fa-trash-o"></i> Delete</button>';
}
}
You haven't posted all your markup but I believe this is your problem:
You are not retreiving the localStorage correctly. You are saving a stringified version of a JSON object and then you are trying to access it directly as an object.
Instead, you need to retrieve the localstorage item and parse it back to a JSON object, then iterate through it or access its properties as an object.
Replace:
cell.innerHTML = localStorage.key(i);
With:
json = JSON.parse(localStorage.key(i));
cell.innerHTML = json.latlng;// or json.address or json.image;
Hope this helps!

Categories

Resources