|
Looks like an old codebase using PHP and jQuery. Just FYI, rather than dump all your code, perhaps start with just the relevant bits? It shows us you put some effort into this.
Anywho, that JSON object will only have a string in it. If that string is a path to an image, you'll have to output that path in its src attribute, similar to the way you're building out that table.
const output = `<img src="${object.path}" />`;
element.innerHTML += output;
Note: There are better ways to go about this, but I'll save that for a different day.
Jeremy Falcon
modified 24-Jan-23 13:34pm.
|
|
|
|
|
hi.
we need to make software access control using device ZKTECO.
with language java.
us possible to help.
best regards
|
|
|
|
|
1) Despite the similar names, Java and JavaScript are completely different languages. You have posted this question in the JavaScript forum, despite saying you want to use Java.
2) If you want help, then you need to describe precisely what you are trying to do, show the code you have tried, and explain what the problem is and where you are stuck. Nobody here is going to do your work for you!
3) The best place to start with questions on a specific device is to ask the device manufacturer.
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Hello! I want to say that I just started working with nodejs. I used before php/laravel.
I have 2 tables, one is for posts one is for posts_actions . Every user can create a post and other users can like/comment on that post. Every action on that post (eg: like) will be stored in table posts_actions.
I'm trying to load the posts from database, loop through them to add an extra object with all the data from table posts_actions.
But at the end, when I send back the data to frontend, the data is empty, why is that and how can I solve this?
app.post("/api/loadposts", function(req, res) {
let posts = [];
let posts_actions = [];
const userid = req.body.userID;
db.query("SELECT * FROM posts ORDER BY id DESC",
(error, result) => {
if(error) {
return res.status(200).send({ error: true });
}
posts = result;
});
for(let p; p < posts.length; p++)
{
db.query("SELECT * FROM posts_actions WHERE post_id = ? AND user_id = ? LIMIT 1", [posts[p].id, userid],
(e, r) => {
if(e) {
posts[p].action = [];
}
else if(r.length > 0) {
posts[p].action = r[0];
}
else {
posts[p].action = [];
}
});
}
res.status(200).send({ data: posts });
});
I know that I must use async/await/promise , I followed some topics and tried the code below, but the data I send to frontend is empty.
A little help here, what can I do to have the result I want?
async function doQuery(query, params = []) {
function queryData(query, params) {
return new Promise(function(resolve, reject) {
db.query(query, params, function (err, rows, fields) {
if (err) {
return reject(err);
}
resolve(rows);
});
});
}
queryData(query, params).then(function(v) {
return v;
}).catch(function(v) {
return [];
})
return null;
}
async function getAllPosts(userid)
{
try {
let posts = await doQuery("SELECT * FROM posts ORDER BY id DESC");
for(let p = 0; p < posts.length; p++)
{
let actions = await doQuery("SELECT * FROM posts_actions WHERE post_id = ? AND user_id = ? LIMIT 1", [posts[p].id, userid]);
if(actions.length)
{
posts[p].actions = actions[0];
}
else
{
posts[p].actions = [];
}
}
return posts;
} catch (error) {
return error;
}
}
app.post("/api/loadposts", async function(req, res)
{
let posts = await getAllPosts(req.body.userID);
res.send({ data: posts });
});
modified 12-Jan-23 6:11am.
|
|
|
|
|
Your doQuery function always returns null . You need to start by fixing that:
function doQuery(query, params = []) {
return new Promise(function(resolve, reject) {
db.query(query, params, function (err, rows, fields) {
if (err) {
reject(err);
} else {
resolve(rows);
}
});
});
} With that change in place, your other code should work - although you'll probably want to catch any errors thrown when you load the actions for an individual post, rather than throwing all of the posts away.
If your database supports it, you may also want to load the post actions in parallel, rather than serially:
async function loadPostActions(post, userid) {
try {
post.actions = await doQuery("SELECT * FROM posts_actions WHERE post_id = ? AND user_id = ? LIMIT 1", [post.id, userid]);
} catch (error) {
post.actionsError = error;
}
}
async function getAllPosts(userid)
{
try {
const posts = await doQuery("SELECT * FROM posts ORDER BY id DESC");
const actionPromises = [];
for (let p = 0; p < posts.length; p++) {
actionPromises.push(loadPostActions(posts[p], userid));
}
await Promise.all(actionPromises);
return posts;
} catch (error) {
return error;
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you very very much! That works perfectly!
But apparently, on postman the data I receive is good, but on frontend the action object inside data is empty and it shouldn't be.
This is what I get with postman :
{
"data": [
{
"id": 2,
"user_id": 1,
"text": "d2222222",
"posted_at": "1/12/2023 1:52:27 PM",
"likes": 1,
"comments": 0,
"picture": "",
"userid": 1,
"name": "Gilbert",
"actions": [
{
"id": 1,
"tweet_id": 2,
"user_id": 1,
"liked": 1,
"retweeted": 0,
"replied_count": 0
}
]
}
]
}
And on frontend (Reactjs):
{
"data": [
{
"id": 2,
"user_id": 1,
"text": "d2222222",
"posted_at": "1/12/2023 1:52:27 PM",
"likes": 1,
"comments": 0,
"picture": "",
"userid": 1,
"name": "Gilbert",
"actions": []
}
]
}
useEffect(() => {
loadAllPosts();
}, [])
function loadAllPosts() {
Axios.post('/api/loadposts', {
userID: loginData.id
}).then((response) => {
console.log(response.data.data)
setPosts(response.data.data);
}).catch((error) => {
console.log("Something went wrong.. We are investigating.");
})
}
modified 12-Jan-23 8:36am.
|
|
|
|
|
That's odd; if it works for one, it should work for the other.
You could try loading the actions serially, in case Node has a problem with Promise.all :
async function getAllPosts(userid)
{
try {
const posts = await doQuery("SELECT * FROM posts ORDER BY id DESC");
for (let p = 0; p < posts.length; p++) {
await loadPostActions(posts[p], userid);
}
return posts;
} catch (error) {
return error;
}
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
I solved this. I needed to put an if statment on useEffect if the user is logged (because I couldn't get his userID in the beginning to send a post request).
useEffect(() => {
if(loginStatus === true) {
loadAllPosts();
}
}, [loginStatus])
Thank you very very much @RichardDeeming for helping me out!
Btw, loading parallel in my "context" lets says, is more efficient (memory, loading time, etc) instead of serially? Or is just because using serially will throw all posts if a promise is rejected (fail)?
|
|
|
|
|
Member 15892067 wrote: Btw, loading parallel in my "context" lets says, is more efficient (memory, loading time, etc) instead of serially? Or is just because using serially will throw all posts if a promise is rejected (fail)?
Loading in parallel should be faster, if the database supports it. You're telling it to start loading the actions for all posts, then waiting for them all to finish, rather than waiting for it to load the actions for the first post, then waiting for it to load the actions for the second post, ...
For example, assume it took an average of 50ms to load the actions for one post, and you want to load the actions for 10 posts. Doing that serially would take around 500ms. Doing it in parallel should take around 50ms.
This article is about C#, but many of the same principals apply:
Making an Asynchronous Breakfast in .NET[^]
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Couple things to consider here. First and foremost, do not use successive round trips in an API call as your first solution. It's always a last resort. It's much quicker to doing a JOIN on you indexes to combine the data. Yes this first payload be larger, but you only need to establish the connection once and you're still using the same sized payload even if it's split up into calls. So, the proper solution is to use a query or view and return that info to the client (the client being the Express server in this instance) in one trip... you can paginate if you need to break up the payload size into several calls.
To answer your question, and I do not suggest you do that this at all, but to address it...
In your doQuery function, notice that only the reject case in returned in your closure. Not the cause of your issue, but to be consistent. Also, the function doesn't need to return an explicit promise. It's being done already under the hood. Use try/catch in your async functions to handle error conditions. The syntax is much cleaner.
async function doQuery(query, params = []) {
try {
return await new Promise((resolve, reject) => {
db.query(query, params, (err, rows) => {
if (err)
reject(err);
else
resolve(rows);
});
});
} catch {
return [];
}
}
If your data is still null after reworking that routine than make sure db.query is returning valid data.
Also, if you plan on making successive calls like this, you'd be much, much better off using generators . But, that is a last choice. You should be redoing your DB design and queries first.
Jeremy Falcon
|
|
|
|
|
Now you are using SQL database with nodejs and created 2 tables to store post data.
Sometimes, SQL DB is more effective than no-SQL DBs like mongoDB but in your case, the best optimized method is using MongoDB.
By its property, mongoDB is the fittest one for your current project.
If you need to use only SQL DB, you can consider about ORM in SQL DB.
Wish your good.
|
|
|
|
|
What are the limits of HTML? Can you build anything with HTML and CSS that you can build with Java Script?
|
|
|
|
|
Not necessarily as HTML/CSS and Javascript are totally different products.
|
|
|
|
|
how to validate date in calender 15 days before & after
|
|
|
|
|
You're going to have to describe what you mean by "validate" in this context.
Like, are you using todays date and trying to get the date 15 days before that and after?
|
|
|
|
|
|
It's been long enough, so even if this was a homework question, it was probably due already. Soooooo, here ya go. I haven't tested this, but there shouldn't be a bug. Either way, it should at least you get started.
const DATE_OFFSET = 1080000000;
const someDate = Date.parse('25 Dec 2022 00:00:00');
const now = new Date();
const fifteenDaysAgo = new Date(now.getTime() - DATE_OFFSET);
const fifteenDaysFromNow = new Date(now.getTime() + DATE_OFFSET);
console.log((someDate >= fifteenDaysAgo) && (someDate <= fifteenDaysFromNow));
Jeremy Falcon
|
|
|
|
|
If you haven't checked out MDN yet, it's an awesome resource. It's always worth a search or read to see what a built-in JavaScript object can do...
MDN Web Docs
Jeremy Falcon
|
|
|
|
|
Hello & TIA ;
Create a Draggable Clone from id="elem1" , where id="elem1" is draggable="false"; .
The coding problem is here : clone.classList.add('draggable="true"')
Please What is the proper coding ?
Thanks
function cloneElem1(){
var elem = document.querySelector('#elem1');
var clone = elem.cloneNode(true);
clone.id = 'elem2' + elemNumber;
elemNumber = elemNumber + 1
clone.classList.add('text-large');
clone.classList.add("draggable='true';")
elem.after(clone);
}
</script>
********
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Guitar-Scales-and-Boxes-Builder-4-Circles-4-Frets-CLONE.html</title>
<!-- https:
<style>
body {
margin: 20px;
background-color: #FFFFFF;
}
.flex-container {
display: flex;
}
.flex-container > div {
font-size: 20px;
}
#container {
width: 100%;
height: 100px;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
counter-reset: itemCount;
}
.item {
display: inline-block;
border-radius: 50%;
touch-action: none;
user-select: none;
counter-increment: itemCount;
content: 'count' + itemCount;
width: 32px;
height: 32px;
background-color: #F5F5F5;
font-family: Arial, Helvetica, sans-serif;
text-align:center;
font-size:28px;
z-index: 8;
}
.flatOne , .sharpOne , .naturalOne { background-color: #DCDCDC;
z-index: 5;
}
td {margin: auto;
}
#elem1 , #elem2 , #elem3 , #elem4(
)
.flatOne , .one , .sharpOne , naturalOne {
}
#itemContainer { }
#tableContainer { }
#fretboardContainer { background-color: #DCDCDC;
}
tbody { background-color:#636363;
}
#tbodyId { background-color:#636363;
}
.item:active {
opacity: .75;
}
.item:hover {
cursor: pointer;
}
</style>
</head>
<body>
<div id="outerContainer" ondrop="drop(event)" ondragover="allowDrop(event)" style="background-color: pink; top: 4px; left: 4px; height:200px; border: 4px;"> <!-- BEGIN OF id="outerContainer -->
<div>
X: <span id="x"></span><br>
Y: <span id="y"></span>
</div>
<!-- BEGIN of id="itemContainer" -->
<div id="itemContainer" class="flex-container POS" style=" position: absolute; left: 500px; top; 40px; ">
<div class="item flatOne" id="elem1" onclick="cloneElem1()" style=" z-index:5; left: 100px; background-color: #DCDCDC" > b</div>
<p> </p>
<div class="item one" id="elem2" style=" z-index:5; left: 400px; background-color: #FF0004;" > 1</div>
<p> </p>
<div class="item sharpOne" id="elem3" style=" z-index:5; left: 700px; background-color: #DCDCDC;" > ♯</div>
<p> </p>
<div class="item naturalOne" id="elem4" style=" z-index:5; left: 1000px; background-color: #DCDCDC;" > ♮</div>
</div> <!-- END of id="itemContainer" -->
<div id="tableContainer" style=" position: absolute; top: 155px; left: 55px; "> <!-- BEGIN of id="tableContainer" -->
<table id="fretboardContainer" style=" position: absolute ; width: 1200px;"> <!-- BEGIN of id="fretContainer" -->
<!-- Start Copy Here -->
<tbody id="tbodyId" style="background-color:#636363;">
<tr style="height: 40px; border-bottom: 2px solid red; border-top: 3px solid white;">
<!-- Row 1 -->
<td id="r1f1" ondrop="drop(event)" ondragover="allowDrop(event)" style="margin: auto; vertical-align: top; border-bottom: 3px solid white; border-top: 4px solid white;"><br>
</td>
<td id="r1f2" ondrop="drop(event)" ondragover="allowDrop(event)" style="margin: auto; vertical-align: top; border-bottom: 2px solid white; border-top: 4px solid white;"><br>
</td>
<td id="r1f3" ondrop="drop(event)" ondragover="allowDrop(event)" style="margin: auto; vertical-align: top; border-bottom: 2px solid white; border-top: 4px solid white;"><br>
</td>
<td id="r1f4" ondrop="drop(event)" ondragover="allowDrop(event)" style="margin: auto; vertical-align: top; border-bottom: 2px solid white; border-top: 4px solid white;"><br>
</td>
</tr>
</tbody>
</table> <!-- END OF fretContainer -->
</div> <!-- END OF tableContainer -->
</div> <!-- END OF id="outerContainer -->
<div style='text-align: center; position:absolute; bottom: 40px;'>Drag and Drop</div>
<!-- BEGIN SCRIPT ZZZZZZZZZZZZZZZZZ -->
<script>
window.addEventListener('mousemove', (event) => {
let x = event.clientX;
let y = event.clientY;
document.getElementById('x').innerHTML = x;
document.getElementById('y').innerHTML = y;
});
</script>
<script>
var elemNumber = 0;
</script>
<script>
function cloneElem1(){
var elem = document.querySelector('#elem1');
var clone = elem.cloneNode(true);
clone.id = 'elem2' + elemNumber;
elemNumber = elemNumber + 1
clone.classList.add('text-large');
clone.classList.add("draggable="true"")
elem.after(clone);
}
</script>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
console.log("function function drag(ev)")
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
console.log("function drop(ev)")
}
</script>
</body>
</html>
|
|
|
|
|
|
Instructions:
Go to here: https://vmars.us/Guitar/Guitar-Scales-and-Boxes-Builder-4-Circles-4-Frets-CLONE.html
Open up Console
Click on the 'b' grey circle
Drag the Cloned 'b' grey circle onto the Dark Grey Fretboard .
See Errors in Console.log .
Thanks
These are Errors I am getting .
Code:Copy to clipboard
Guitar-Scales-and-Boxes-Builder-4-Circles-4-Frets-CLONE.html:169 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at drop (Guitar-Scales-and-Boxes-Builder-4-Circles-4-Frets-CLONE.html:169:13)
at HTMLTableCellElement.ondrop (Guitar-Scales-and-Boxes-Builder-4-Circles-4-Frets-CLONE.html:108:171)
Guitar-Scales-and-Boxes-Builder-4-Circles-4-Frets-CLONE.html:169 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at drop (Guitar-Scales-and-Boxes-Builder-4-Circles-4-Frets-CLONE.html:169:13)
at HTMLDivElement.ondrop (Guitar-Scales-and-Boxes-Builder-4-Circles-4-Frets-CLONE.html:82:160)
|
|
|
|
|
|
Hello & TIA
Need help , Having problem with Drag n Drop ?
My code seems quite simple , but I have been hung up for days :
The first DnD doesnt Drop : 'div id="itemContainer" ' , getting Errors:
Guitar-Scales-and-Boxes-Builder-4-Note-4-Frets-CLONE-MINIMAL.html:131 Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
at drop (Guitar-Scales-and-Boxes-Builder-4-Note-4-Frets-CLONE-MINIMAL.html:131:16)
at HTMLTableElement.ondrop (Guitar-Scales-and-Boxes-Builder-4-Note-4-Frets-CLONE-MINIMAL.html:78:132)
The Second DnD runs fine .
<pre><!DOCTYPE HTML>
<html>
<head>
<style>
#div1, #div2 {
float: left;
width: 100px;
height: 35px;
margin: 10px;
padding: 10px;
border: 1px solid black;
}
.item {
display: inline-block;
border-radius: 50%;
touch-action: none;
user-select: none;
counter-increment: itemCount;
content: 'count' + itemCount;
width: 32px;
height: 32px;
font-family: Arial, Helvetica, sans-serif;
text-align:center;
font-size:28px;
z-index: 8;
}
</style>
</head>
<body>
<h2>Drag and Drop</h2>
<br>
<div id="itemContainer" id="dragItems" ondrop="drop(event)" ondragover="allowDrop(event)" class="POS" style=" width:100%; border: thick solid pink;">
<br> <div class="item" class="flatOne" id="flatOne" draggable="true" style=" background-color: yellow;" >b1</div>
<br> <div class="item" class="one" draggable="true" ondragstart="drag(event)" style=" background-color: #FF0004;" > 1</div>
<br> <div class="item" class="sharpOne" draggable="true" ondragstart="drag(event)" style=" background-color: yellow;" >♯1</div>
<br> <div class="item" class="naturalOne" draggable="true" ondragstart="drag(event)" style=" background-color: yellow;" >♮1</div>
</div>
<div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)">
<img src="RedCircle.png" draggable="true" ondragstart="drag(event)" id="drag1" width="88" height="31">
</div>
<div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
<br><br><br><br>
<br>
<div ondrop="drop(event)" ondragover="allowDrop(event)" style=" border: thick solid blue; width:100%; height: 200px;">
</div>
<script>
function allowDrop(ev) {
ev.preventDefault();
}
function drag(ev) {
ev.dataTransfer.setData("text", ev.target.id);
console.log("function function drag(ev)")
}
function drop(ev) {
ev.preventDefault();
var data = ev.dataTransfer.getData("text");
ev.target.appendChild(document.getElementById(data));
console.log("function drop(ev)")
}
</script>
</body>
</html>
https://vmars.us/ShowMe/Drag-n-Drop.mp4
modified 21-Dec-22 20:34pm.
|
|
|
|
|
Only one of your draggable elements has an id . For any of the others, you set the dataTransfer data to an undefined value. When you drop that, you call getElementById(undefined) , which returns null . You then pass null to appendChild , which throws the error.
Add a unique id to every element you want to drag, and validate the element when you drop it.
let uid = 0;
function drag(ev) {
const id = e.target.id;
if (!id) {
id = `_auto_generated_id_${uid}`;
e.target.id = id;
uid++;
}
ev.dataTransfer.setData("text", id);
console.debug("drag", e.target, id);
}
function drop(ev) {
ev.preventDefault();
const id = ev.dataTransfer.getData("text");
if (!id) {
console.warn("Drop with no ID", ev.dataTransfer);
return;
}
const element = document.getElementById(id);
if (!element) {
console.warn("Element not found", id);
return;
}
ev.target.appendChild(element);
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Richard Thank you very much...
Ah yes , id="" .
Originally , I used this code:
<script>
var container = document.querySelector("#itemContainer");
var activeItem = null;
var active = false;
container.addEventListener("touchstart", dragStart, false);
container.addEventListener("touchend", dragEnd, false);
container.addEventListener("touchmove", drag, false);
container.addEventListener("mousedown", dragStart, false);
container.addEventListener("mouseup", dragEnd, false);
container.addEventListener("mousemove", drag, false);
function dragStart(e) {
if (e.target !== e.currentTarget) {
active = true;
activeItem = e.target;
if (activeItem !== null) {
if (!activeItem.xOffset) {
activeItem.xOffset = 0;
}
if (!activeItem.yOffset) {
activeItem.yOffset = 0;
}
if (e.type === "touchstart") {
activeItem.initialX = e.touches[0].clientX - activeItem.xOffset;
activeItem.initialY = e.touches[0].clientY - activeItem.yOffset;
} else {
console.log("Dragging something!");
activeItem.initialX = e.clientX - activeItem.xOffset;
activeItem.initialY = e.clientY - activeItem.yOffset;
}
}
}
}
function dragEnd(e) {
if (activeItem !== null) {
activeItem.initialX = activeItem.currentX;
activeItem.initialY = activeItem.currentY;
}
active = false;
activeItem = null;
}
function drag(e) {
if (active) {
if (e.type === "touchmove") {
e.preventDefault();
activeItem.currentX = e.touches[0].clientX - activeItem.initialX;
activeItem.currentY = e.touches[0].clientY - activeItem.initialY;
} else {
activeItem.currentX = e.clientX - activeItem.initialX;
activeItem.currentY = e.clientY - activeItem.initialY;
}
activeItem.xOffset = activeItem.currentX;
activeItem.yOffset = activeItem.currentY;
setTranslate(activeItem.currentX, activeItem.currentY, activeItem);
}
}
function setTranslate(xPos, yPos, el) {
el.style.transform = "translate3d(" + xPos + "px, " + yPos + "px, 0)";
}
</script>
But the Cursor keeps loosing the Target , as you can view here ,
https://vmars.us/Guitar/Guitar-Scales-and-Boxes-Builder-1-Note-4-Frets-FORUM.html
Forcing me to keep going back and Grabbing Target again & again .
Which forces me to Drag at a sloth's pace .
Otherwise it works fine for class= .
So I was trying to find a better/FASTER solution , as in RedDot code above ;
unfortunately , I forgot the id= business .
Why not use id= as in here :
https://vmars.us/Guitar/Guitar-Scales-and-Boxes-Builder.html
If you view the html source , you will see that every .item has 6-duplicates ;
which turns out to be 7 x 7 = 49 .items .
So if I use id= I'll have to code 49 unique id='s .
So , I plan to Post a new thread , asking 'For a.js vs b.js , why is a.js so much Faster than b.js ? ' .
Faster meaning , "NOT Grabbing Target again & again " .
Sound reasonable ?
Thanks for your Help...
|
|
|
|
|