|
I have a form that asks users to provide their billing and shipping addresses.
If the billing address is same as the mailing address, click a checkbox to copy the billing address information to mailing address boxes.
So far, address, city and zip are getting copied from billing to mailing addresses but the State address is not getting copy.
The billing State has a hardcoded value of WI for Wisconsin. That NEVER changes, hence it is hardcoded.
The mailing address for State has a DropDownList of states, I am pretty sure that has to do with why the billing address for State is not getting cover over to mailing address for State.
Can you guys please see what I am doing wrong?
Here is what I am working with.
<script type="text/javascript">
$('#SameAsMailing').click(function () {
if ($('input[name="SameAsMailing"]').is(':checked')) {
$('#mailStreetAddress').val($('#instAddress').val());
$('#mailCity').val($('#instAddressCity').val());
var thestate = $('#instAddressState option:selected').val();
if (thestate != "") {
$('#mailState option[value="' + thestate + '"]').prop('selected', true);
}
$('#mailZip').val($('#instAddressZip').val());
}
else
{
$('#mailStreetAddress').val("");
$('#mailCity').val("");
$('#mailState option:eq(0)').prop('selected', true);
$('#mailZip').val("");
}
});
</script>
<asp:TableRow>
<asp:TableHeaderCell CssClass="align-right">Install Address:</asp:TableHeaderCell>
<asp:TableCell><asp:TextBox ID="instAddress" runat="server" /></asp:TableCell>
<asp:TableHeaderCell CssClass="align-right">City:</asp:TableHeaderCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableHeaderCell CssClass="align-right">City:</asp:TableHeaderCell>
<asp:TableCell><asp:DropDownList ID="instAddressCity" OnSelectedIndexChanged="instAddressCity_Changed" AutoPostBack="true" runat="server" /></asp:TableCell>
<asp:TableHeaderCell CssClass="align-right">State:</asp:TableHeaderCell>
<asp:TableCell CssClass="align-left"><asp:Label ID="instAddressState" runat="server" Text="WI" /></asp:TableCell>
<asp:TableHeaderCell CssClass="align-left">Zip:</asp:TableHeaderCell>
<asp:TableCell><asp:DropDownList ID="instAddressZip" runat="server" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableHeaderCell CssClass="align-right">Address:</asp:TableHeaderCell>
<asp:TableCell><asp:TextBox ID="mailStreetAddress" runat="server" /></asp:TableCell>
<asp:TableHeaderCell CssClass="align-right">City:</asp:TableHeaderCell>
<asp:TableCell><asp:TextBox ID="mailCity" runat="server" /></asp:TableCell>
</asp:TableRow>
<asp:TableRow>
<asp:TableHeaderCell CssClass="align-right">State:</asp:TableHeaderCell>
<asp:TableCell><asp:DropDownList ID="mailState" runat="server"></asp:DropDownList></asp:TableCell>
<asp:TableHeaderCell CssClass="align-right">Zip:</asp:TableHeaderCell>
<asp:TableCell><asp:TextBox ID="mailZip" runat="server" /></asp:TableCell>
</asp:TableRow>
Many thanks in advance
|
|
|
|
|
samflex wrote:
var thestate = $('#instAddressState option:selected').val();
if (thestate != "") {
$('#mailState option[value="' + thestate + '"]').prop('selected', true);
} Try:
var thestate = $('#instAddressState').val();
if (thestate !== "") {
$('#mailState').val(thestate);
}
"These people looked deep within my soul and assigned me a number based on the order in which I joined."
- Homer
|
|
|
|
|
Thank you for your response sir but it did not work.
In other words, the value of WI did not get copied to the mailState DropDownList.
I tried hardcoding the State value since that will always be the same like this:
var thestate = 'WI';
if (thestate !== "") {
$('#mailState').val(thestate);
}
It appears to change something on the mailState dropdownlist but did not display that WI value in the dropdown.
Instead, it showed blank value as the selected value on the mailState dropdownlist box.
modified 13-Feb-23 11:38am.
|
|
|
|
|
Hi all,
I’ve two issues
The first one:
as you can see in the second image (when cloning select input with select2 plugin, the cloned input appears with (the first disabled item appended next to the main input in every row)).
[Original row image]
[My issue image]
the second issue:
I’ve ajax code to append “unit menu” based on “product menu” selection
when I create a new row, and select an item from “product menu” I expected that the “unit menu” of the same row must affect and append the “unit list” belongs to the selection of the "product menu" in the same row.
But the behavior according to the next code is very different (after cloning the main row, when I select a product the appended unit list (appears in all unit menu in every row) and after I used ("this" or "the new created class") I get an empty "unit menu" in the new rows (i.e when select a product no changes takes place in the "unit menu")
Only the first row works (select a product append a menu to "unit input menu")
### js.html file
<script>
$(document).ready(function() {
var purchase = $('.purchase-row').last().clone();
let purchaseCount = 0;
$(document).on('click', '.add_item', function() {
var clone = purchase.clone();
console.log('clone: ', clone);
$(this).prevAll('.purchase-row').first().after(clone.hide());
clone.slideDown('fast');
$('.purchase-row').find('#id_pro-product').removeClass('product').addClass('newProduct');
$('.purchase-row').find('#id_pro-unit').removeClass('unit').addClass('newUnit');
$('.purchase-row').find('#id_pro-product').addClass('product_'+ purchaseCount);
$('.purchase-row').find('#id_pro-unit').addClass('unit_'+ purchaseCount);
var $example = $(".newProduct").select2();
$example.select2();
purchaseCount++;
console.log('PURCHASE-COUNT: ', purchaseCount);
});
$(document).on('click', '.purchase-minus', function() {
if (purchaseCount == 0) {
alert('You can not delete this row' );
} else {
$(this).closest('.purchase-row').remove();
purchaseCount--;
console.log('PURCHASE-COUNT2: ', purchaseCount);
}
});
$(document).on('click', '.purchase-broom', function() {
$(this).closest('.newProduct').select2('destroy');
$(this).closest('.purchase-row').find('select')[0].selectedIndex=0;
});
$(document).on('change', '.product', function(e){
var product_id = $(this).val();
console.log('SUCCESS-CHANGE-PRODUCT: ', product_id);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_product_unit" %}',
data: {
'pro-product': $('.purchase-row select').closest('.product').val(),
},
success: function (data) {
console.log(
'FROM SUCCESS: ', data['unit'],
);
var values_3 = data['unit'];
$('select').closest('.unit').text('');
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
$('select').closest('#id_pro-unit').append('<option>' + values_3[i] + '</option>');
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase !!!');
},
});
e.preventDefault();
});
$(document).on('change', '.newProduct', function(e){
var product_id = $(this).val();
var $this = $(this);
console.log('SUCCESS-CHANGE-PRODUCT-FROM-NEW-CLASS: ', product_id);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_new_row_unit" %}',
data: {
'pro-product': product_id,
},
success: function (data) {
console.log(
'FROM SUCCESS-NEW-CLASS: ', data['unit'],
'PRODUCT-FROM-NEW-CLASS: ', data['product'],
);
var values_3 = data['unit'];
$('select').closest('.unit_'+purchaseCount).text('');
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
$('.purchase-row select').closest('.unit_'+ purchaseCount).append('<option>' + values_3[i] + '</option>');
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase-New Class !!!');
},
});
e.preventDefault();
});
});
</script>
[Pastebin link]
[Codepen link]
By the way I'm using Django so the inputs will not appear correctly in codepen link
Sorry for prolongation.... Thanks
Amr Aly
|
|
|
|
|
Finally I fix my issue as usual. I want to share my solution of this issue.
$(document).on('change', '.product', function(e){
var product_id = $(this).val();
let $el = $(this).closest('.purchase-row');
console.log('SUCCESS-CHANGE-PRODUCT: ', product_id,);
$.ajax({
type: 'POST',
url: '{% url "purchases:get_product_unit" %}',
data: {
'pro-product': product_id,
},
success: function (data) {
if (purchaseCount == 0) {
console.log('purchase count equal to ZERO: ');
console.log(
'FROM SUCCESS: ', data['unit'],
);
var values_3 = data['unit'];
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
$el.find('.unit').append('<option>' + values_3[i] + '</option>');
}
}
} else {
let unit = $el.find('.newUnit');
var values_3 = data['unit'];
unit.text('');
console.log('COUNT IS NOT EQUAL TO ZERO:', values_3);
if (values_3.length > 0) {
for (var i = 0; i < values_3.length; i++) {
unit.append('<option>' + values_3[i] + '</option>');
}
}
}
},
error: function (){
console.log('ERROR with ajax request in Adding Purchase !!!');
},
});
e.preventDefault();
});
Or in an enhanced code snippet as follow
$(document).on("change", ".product", function (e) {
var product_id = $(this).val();
let $el = $(this).closest(".purchase-row");
console.log("SUCCESS-CHANGE-PRODUCT: ", product_id);
$.ajax({
type: "POST",
url: '{% url "purchases:get_product_unit" %}',
data: {
"pro-product": product_id
},
success: function (data) {
const values_3 = data.unit;
const unitClass = purchaseCount == 0 ? ".unit" : ".newUnit";
const unit = $el.find(unitClass);
unit.text('');
if (values_3.length) {
for (const value of values_3) {
unit.append(`<option>${value}</option>`);
}
}
},
error: function () {
console.log("ERROR with ajax request in Adding Purchase !!!");
}
});
e.preventDefault();
});
|
|
|
|
|
Hi everyone,
I wrote this great script to help my team set up the weekly task distribution board, I wrote it using java script, html, and css, they've been doing it for a very long time in pencil on paper. but now i am in the final stage, i would like to convert my table to pdf, and this is where i found it difficult, i did several tests : like convert csv to pdf, it doesn't always give a good table, as it is under html. I would like to add a column at the end of the table for remarks but I think I will try with it later. now i'm just focus on pdf export. to be able to print our table every week and hang it, instead of pencil and a paper.
<pre>
<table id="timetable">
<body>
<tr>
<td>
<link href="table.css" rel="stylesheet">
<script src="table.js"></script>
</td>
<tr>
<button onclick="exportCSV()">Export CSV</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<button onclick="exportPDF()">Export PDF</button>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/pdfmake.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/pdfmake/0.1.77/vfs_fonts.js"></script>
</body>
const timetable = document.getElementById("timetable");
const days = ["Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"];
const hours = ["7H", "13H", "20H"];
const daysHeaderRow = document.createElement("tr");
const daysHeaderCell = document.createElement("th");
daysHeaderCell.innerHTML = "Days";
daysHeaderRow.appendChild(daysHeaderCell);
days.forEach(day => {
const dayHeaderCell = document.createElement("th");
dayHeaderCell.innerHTML = day;
dayHeaderCell.colSpan = 3;
daysHeaderRow.appendChild(dayHeaderCell);
});
timetable.appendChild(daysHeaderRow);
const hoursHeaderRow = document.createElement("tr");
const hoursHeaderCell = document.createElement("th");
hoursHeaderCell.innerHTML = "Hours";
hoursHeaderRow.appendChild(hoursHeaderCell);
for (let i = 0; i < days.length; i++) {
for (let j = 0; j < 3; j++) {
const hourHeaderCell = document.createElement("th");
hourHeaderCell.innerHTML = hours[j];
hoursHeaderRow.appendChild(hourHeaderCell);
}
}
timetable.appendChild(hoursHeaderRow);
const names = ["Khalfi","Redouani", "Daki", "Hamma", "Saadane", "Boughanem", "El Ansari","Badilou","Raoui", "Chouiba", "Dahmane", "Achdad", "Bouryal", "Ettouri", "Saadouni"];
for (let name of names) {
const row = document.createElement("tr");
const nameCell = document.createElement("td");
nameCell.innerHTML = name;
row.appendChild(nameCell);
for (let i = 0; i < days.length; i++) {
for (let j = 0; j < 3; j++) {
const cell = document.createElement("td");
const select = document.createElement("select");
select.classList.add("cell");
const options = [" ", "CP", "ME", "CL", "CE", "R"];
options.forEach(option => {
const optionElement = document.createElement("option");
optionElement.value = option;
optionElement.innerHTML = option;
select.appendChild(optionElement);
});
cell.appendChild(select);
row.appendChild(cell);
}
}
timetable.appendChild(row);
}
function exportCSV() {
var rows = document.querySelectorAll("#timetable tr");
var csvData = [];
for (var i = 0; i < rows.length; i++) {
var rowData = [];
var cells = rows[i].querySelectorAll("td, th");
for (var j = 0; j < cells.length; j++) {
const select = cells[j].querySelector("select");
if(select){
rowData.push(select.value);
}else{
rowData.push(cells[j].innerText);
}
}
csvData.push(rowData);
}
var csv = Papa.unparse(csvData);
var csvData = new Blob([csv], {type: 'text/csv;charset=utf-8;'});
var csvURL = null;
if (navigator.msSaveBlob) {
csvURL = navigator.msSaveBlob(csvData, 'timetable.csv');
} else {
csvURL = window.URL.createObjectURL(csvData);
}
var tempLink = document.createElement('a');
tempLink.href = csvURL;
tempLink.setAttribute('download', 'timetable.csv');
tempLink.click();
var pdf = new jsPDF('l','mm','a4');
pdf.addPage();
pdf.text(csv, 10, 10);
pdf.save('timetable.pdf');
#timetable th {
border: 1px solid #ddd;
padding: 8px;
text-align: center;
background-color: #006699;
}
body {
background-color: #f1f1f1;
font-family: Arial, sans-serif;
margin: 0;
padding: 0;
}
nav {
background-color: #333;
color: #fff;
display: flex;
justify-content: space-between;
padding: 10px 20px;
}
nav a {
color: #fff;
text-decoration: none;
margin-right: 10px;
}
main {
padding: 20px;
}
h1, h2, h3 {
color: #333;
text-align: center;
margin-bottom: 20px;
}
p {
line-height: 1.5;
margin-bottom: 20px;
}
img {
max-width: 100%;
}
|
|
|
|
|
Congrats?
Jeremy Falcon
|
|
|
|
|
|
Hello,
I successfully loaded the json responses into an HTML table. However, I am having a problem displaying the images of the json variables. I could only display the links. Here is the output:
Home Team Match Date Away Team
https://media-3.api-sports.io/football/teams/2939.png 2023-01-22T20:30:00+03:00 https://media-3.api-sports.io/football/teams/2934.png
https://media-3.api-sports.io/football/teams/2938.png 2023-01-26T21:00:00+03:00 https://media-3.api-sports.io/football/teams/2939.png
https://media.api-sports.io/football/teams/2931.png 2023-02-03T17:00:00+03:00 https://media.api-sports.io/football/teams/2939.png
https://media.api-sports.io/football/teams/2937.png 2023-02-09T19:30:00+03:00 https://media-3.api-sports.io/football/teams/2939.png
https://media-3.api-sports.io/football/teams/2939.png 2023-02-17T17:00:00+03:00 https://media-3.api-sports.io/football/teams/2936.png
Here is a sample of the json file:
<pre>array (
'api' =>
array (
'results' => 10,
'fixtures' =>
array (
0 =>
array (
'fixture_id' => 932017,
'league_id' => 4633,
'league' =>
array (
'name' => 'Pro League',
'country' => 'Saudi-Arabia',
'logo' => 'https://media-3.api-sports.io/football/leagues/307.png',
'flag' => 'https://media-3.api-sports.io/flags/sa.svg',
),
'event_date' => '2023-01-22T20:30:00+03:00',
'event_timestamp' => 1674408600,
'firstHalfStart' => NULL,
'secondHalfStart' => NULL,
'round' => 'Regular Season - 14',
'status' => 'Not Started',
'statusShort' => 'NS',
'elapsed' => 0,
'venue' => 'Mrsool Park',
'referee' => NULL,
'homeTeam' =>
array (
'team_id' => 2939,
'team_name' => 'Al-Nassr',
'logo' => 'https://media.api-sports.io/football/teams/2939.png',
),
'awayTeam' =>
array (
'team_id' => 2934,
'team_name' => 'Al-Ettifaq',
'logo' => 'https://media.api-sports.io/football/teams/2934.png',
),
'goalsHomeTeam' => NULL,
'goalsAwayTeam' => NULL,
'score' =>
array (
'halftime' => NULL,
'fulltime' => NULL,
'extratime' => NULL,
'penalty' => NULL,
),
),
And here is the code for importing the json output into the HTML table:
<pre><script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">
<style>
th{
color:#fff;
}
</style>
<table class="table table-striped">
<tr class="bg-info">
<th>Home Team</th>
<th>Match Date</th>
<th>Away Team</th>
</tr>
<tbody id="myTable">
</tbody>
</table>
<script>
var myArray = []
$.ajax({
method:'GET',
url:'https://api-football-v1.p.rapidapi.com/v2/fixtures/team/2939/next/10?rapidapi-key={API-Key}',
success:function(response){
myArray = response
buildTable(myArray)
console.log(myArray)
}
})
function buildTable(data){
var table = document.getElementById('myTable')
for (var i = 0; i < data.api.fixtures.length; i++){
const rm = data.api.fixtures[i];
var row = `<tr>
<td>${rm.homeTeam.logo}</td>
<td>${rm.event_date}</td>
<td>${rm.awayTeam.logo}</td>
</tr>`
table.innerHTML += row
}
}
</script>
As you can see, I need to show the images of homeTeam.logo and awayTeam.logo instead of their hyperlinks. Thanks in advance
|
|
|
|
|
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?
|
|
|
|
|
|