Category: javascript
Category Added in a WPeMatico Campaign
SvelteKit with FastAPI in DockerCompose
I have an issue understanding how to make an API call to my FastAPI Docker container from SvelteKit Docker container running in Docker-compose and preserve Cookies set by FastAPI.
I need to post a formData with EMAIL and PASSWORD fields from SvelteKit to FastAPI. I’m trying to use Actions in SvelteKit to make the call from the page.server.js
export const actions = {
login: async (event) => {
const formValues = await event.request.formData();
const email = formValues.get("email");
const password = formValues.get("password");
const formData = new FormData();
formData.append("email", email);
formData.append("password", "1");
const res = await event.fetch(
"http://fastapi_backend:8000/web_api/users/sessions",
{
method: "POST",
body: formData,
credentials: "include", // include cookies in the request
}
);
I can extract the cookie from the response and set it to the browser no problem:
const jwt = res.headers.get("set-cookie").split('"')[1];
event.cookies.set("jwt", jwt);
However, when I make another request again I expect the Cookies to be sent with the event.fetch but my FastAPI container does not see any. This is expected as it’s stated in SvelteKit Docs:
Cookies will only be passed through if the target host is the same as the SvelteKit application or a more specific subdomain of it.
SvelteKit Docs
I can not imagine how to do this now. I’m testing this workflow outside of Docker-compose now.
All I know is that if I make this API call from the page.svelte in browser I wouldn’t have access to http://fastapi_backend:8000 which is the Docker-compose name of the FastAPI container.
How should I do this? Is the only real way to do this is to expose the FastAPI container to the outside and make the call from the browser from page.svelte?
Please help!
I’ve tested FastAPI with Postman and it successfully sends and receives cookies.
I’ve also tried making the call from the browser from page.svelte and it works.
Calculator variable multiplications NaN result (more than 2 variables)
So im trying to make a calculator to get into an IT school. But I cant seem to figure out why I get NaN as my answer.
What im supposed to make is a calculator with a feat, the feat being that you can also guess what the answer’ll be. Im stuck trying to figure out why I keep getting NaN as an answer to all my multiplications.
The reason why there is 2 number3’s in my var: product. that is because I found out I needed to have it in the multiplication to do the if statement. number3 is the one you guess withthis is how it looks, i translated the image if anyone was wondering
This is really bugging me since I like doing this but I cant seem to figure it out.
function CalculateProduct() {
var product = parseInt(number1) * parseInt(number2) * parseInt(number3) / parseInt(number3)
var number1 = document.getElementById("number1").value;
var nummer2 = document.getElementById("number2").value;
var number3 = document.getElementById("number3").value
var owncalculation= document.getElementById("owncalculation");
var uitkomst = document.getElementById("uitkomst");
if (number3 == product) {
document.getElementById("owncalculation").innerHTML="The answer you put in was correct"
} else {
document.getElementById("owncalculation").innerHTML="The answer you put in was false"
}
if (Getal3 == product) {
owncalculation.style.color = "green"
} else {
owncalculation.style.color = "red"
}
result.innerHTML = "The answer to " + Getal1 + " * " + Getal2 + " = " + product;
}
React array is always empty during function call, causing duplicate values
I have a function called AddToCart that I’m passing down to a child component called inventoryModal. I want this function to check the existing state array of cart items to make sure the requested productID hasn’t already been added when it’s selected from the inventory modal.
Everything works the way I’m expecting when I add items. BUT, I’m unable to prevent duplicates from being added to the cart. Every time the AddToCart function is called, the cartItems array saved in the state is empty so the item is allowed to be added as a duplicate. I know the cartItems array isn’t empty because I have cartItems appearing on my screen as I click the buttons in the menu.
Below is the function I’m using for AddToCart:
const addToCart = (row) => {
var exist = cartItems.find(currentItem => currentItem.PID === row.values.PID);
if(exist !== undefined){
console.log("Cart Item Already Exists");
}
else {
const newCartItem = { ...row.values };
setCartItems((cartItems) => [...cartItems, newCartItem]);
}
};
Below is the code showing where I’m utilizing the AddToCart function in the child component.
Every row in the table gets “Add To Cart” button appended as a column. So, when a specific row is clicked, that item’s data gets passed to the AddToCart function so it can check for duplicates and add the information to the shopping cart.
const tableHooks = (hooks) => {
hooks.visibleColumns.push((columns) => [
{
id: "Actions",
Header: "Actions",
Cell: ({ row }) => (
<button className="viewBtn" onClick={() => props.addToCart(row)}>
Add To Cart
</button>
),
Filter: ColumnFilter
},
...columns,
]);
};
Below is the structure of an example row that’s being passed to the parent components AddToCart function.
I’ve tried creating a temp array for cartItems before checking the list for a duplicate, and I’ve also tried using findIndex instead of find. But neither has helped. Any advice would be greatly appreciated.
Make a search function in Google Sheets that retrieves row numbers
I am working on a sheet for the game No man’s sky and would like some help with creating a search function since the normal filter function do not work on vertically merged cells.
In R1 i will put in the word/words to search for.
In R2 the function script will be placed and the search result displayed.
The search result i want are what row in the range (R4:R) the word i am searching for exists. so if the word i am searching for in R1 is Cupper, and the word is listed on row 5 8 16 then i want 5, 8, 16, to show up in R2. i would like it if the function was also able to work even if the search words are contained inside dropdowns or if i decide to add a dropdown to the input cell R1.
I have gone through the different functions listed in the function list for Google Sheets but have not ben able to combine the right once to make it work. i am not fluent in JavaScript which is probably why i am finding it hard to make a working script for this.
How can i use the loader and action functions from the react-router-dom package to POST a file to my server?
it’s my first question. Please be forgiving if I have done something wrong.
Setup:
I have a create-react-app which uses the react-router-dom for routing. The main idea is some kind of a simple file server. So the user can upload/drop a file on the webpage. This will be uploaded to a server and should then be listed on the page. For this the server provides an api endpoint which lists all files that were uploaded.
Because i want to use some kind of dropzone, which provides me the File object directly. I will not have a form in the end. So i think for this case i have to choose the useFetcher()
and then run fetcher.submit(...)
.
Problem:
My problem is, that the file is not send to the server. Then I tried to find the source of it.
I think it happens between the two lines with the comment (9 and 27). So the file wrapped inside a FormData gets some how stringified to only the name when passed to the other function.
What I’ve tried
As already mentioned, I checked in which step the problem occurs. So in my eyes it happens somewhere inside the library, which is “submitting” the formData to the action
function. So i looked inside the library, in the file dist/index.js
in the node module (react-router-dom: ^6.10.0) and in line 709 I found a function which can convert the formdata: getFormSubmissionInfo
. But i think because my input is of type FormData it will not be touched and returned in the same way as it was given to the function. (See line 161, dist/index.js
).
Question
Is useFetcher
the correct way to submit a file “in the background” to the server, so no form submit needed?
And if so, how can i provide the file to my action function?
Code snippet:
To seperate the problem from my project I’ve created a github repo of my problem (https://github.com/fabalexsie/StackOverflow_SendFileWithReactRouterDomAction).
The loader and action functions are referenced in the routing object.
export async function loader() {
return fetch('http://localhost:8080/fileList').then(r => r.json())
}
export async function action({request}) {
const formData = await request.formData();
console.log("Formdata in action", formData) // here the file is only the name
await fetch('http://localhost:8080/upload', {
method: 'POST',
body: formData
});
return {success: true};
}
export function Details() {
const fileList = useLoaderData();
const fetcher = useFetcher();
const handleUpload = (ev) => {
const file = ev.target.files[0];
console.log("File from handle upload", file);
const formData = new FormData();
formData.append('file', file);
formData.append('pw', "InRealityComesFromSomeOtherInput");
console.log("Formdata in handle upload", formData); // here the file is the file object
fetcher.submit(formData, {method: 'POST', action: '/details'})
}
return (
<>
<ul>
{fileList.map(f =>
<li key={f}>
<a href={`http://localhost:8080/files/${f}`}>{f}</a>
</li>
)}
</ul>
<input type="file" id="file" name="file" onChange={handleUpload} />
</>
);
}
How can I restrict some exact days of the week with input type=date?
The main problem is that I can select from Monday to Sunday and I want to restrict Tuesdays, Thursdays, Saturdays and Sundays and only select Mondays, Wednesdays and Fridays
This is the code I tried but I don’t actually know why it doesn’t work:
Thanks!!!!!
<form action="insertar_reserva_tarde.php" method="POST">
<label for="fecReserva">Día:</label>
<input type="date" name="fecReserva" id="fecReserva" min="2023-06-15" max="2023-07-15"required>
<br>
<label for="horIniReserva">Hora de inicio:</label>
<select name="horIniReserva" id="horIniReserva">
<option value="17">17:00</option>
<option value="18">18:00</option>
<option value="19">19:00</option>
<option value="20">20:00</option>
</select>
<br>
<label for="horFinReserva">Hora de fin:</label>
<select name="horFinReserva" id="horFinReserva">
<option value="18">18:00</option>
<option value="19">19:00</option>
<option value="20">20:00</option>
<option value="21">21:00</option>
</select>
<br>
<input type="hidden" name="pista" value="1">
<input type="hidden" name="idHorario" value="1">
<input type="submit" value="Reservar">
</form>
<?php
if(isset($_POST['fecReserva'])){
$date = strtotime($_POST['fecReserva']);
$dayOfWeek = date('N', $date); // obtiene el número del día de la semana (1 = lunes, 2 = martes, etc.)
if($dayOfWeek == 1 || $dayOfWeek == 3 || $dayOfWeek == 5){
echo "<p>La fecha seleccionada es el ".date('d/m/Y', $date)."</p>";
} else {
echo "<p>Sólo se permiten reservas en Lunes, Miércoles y Viernes.</p>";
}
}
?>
<script>// Everything except weekend days
const validate = dateString => {
const day = (new Date(dateString)).getDay();
if (day==2 || day==4 || day==6 || day==0 ) {
return false;
}
return true;
}
// Sets the value to '' in case of an invalid date
document.querySelector('input').onchange = evt => {
if (!validate(evt.target.value)) {
evt.target.value = '';
}
}
</script>
The intention is to only select Mondays, Wednesdays and Fridays
I want it to work as much as the value entered from the input
inputField.addEventListener("keyup",(e)=>{
let inputVal=inputField.value;
if(e.key==="Enter" && inputVal.length > 0){
//for(let i=0;i<inputVal;i++){
optionImages.forEach((image,index) => {
image.addEventListener("click",(e)=>{
image.classList.add("active");
userResult.src = cpuResult.src="images/rock.png";
result.textContent= "Wait..."
optionImages.forEach((image2,index2)=>{
if (index!=index2) {
image2.classList.remove("active");
}
});
gameContainer.classList.add("start");
});
});
//}
}
});
I want the code to run as much as the value entered from the input, but when I do it with a for loop, the foreach part continues to run forever.
Can we use pop for string in js
In javascript we can use pop() for arrays. I wish to know if we can do the same for strings.
If not can you please explain why.
Make appear a paragraph and make it disappear when showing the next one on click
I am new at Javascript and I am trying some very basic and simple exercise.
I have three paragraphs and at the click of the button I add a class .visible at one of them.
Now all it does is adding the class at the first loop and remove it at the second loop.
I want it to remove the class at previous paragraph when click again the button.
I know I have to tell to store the array index in a variable so at the second click at that index the class will be removed.
Can anyone help me please?
<div>
<p class="text">I am first</p>
<p class="text">I am second</p>
<p class="text">I am third</p>
</div>
<button value="click me" id="btn">Click me!</button>
const btn = document.getElementById('btn');
const txt = document.querySelectorAll('.text');
let counTxt = 0;
btn.addEventListener('click', function(){
appearTxt();
});
function appearTxt(){
// count array
counTxt = counTxt < txt.length -1 ? ++counTxt: 0;
txt[counTxt].classList.toggle('visible');
};
GeometryType undefined not supported
Mysql is returning Error: GeometryType undefined not supported when I’m trying to get the nearest users to a specified geometry latitude and longitude value. this is my query using sequelize
const location = sequelize.literal(ST_GeomFromText('POINT(${long} ${lat})', 4326)
);
const nearestUsers = await Address.findAll({
where: {
location:[[sequelize.fn('ST_Distance_Sphere', sequelize.literal('geolocation'), location),'distance']],
order: 'distance',
limit: 4
}
})
and this is the address migration file
'use strict';
/** @type {import('sequelize-cli').Migration} */
module.exports = {
async up(queryInterface, Sequelize) {
await queryInterface.createTable('addresses', {
...
location: {
type:Sequelize.GEOMETRY('POINT', 4326),
allowNull:false
},
...
});
},
async down(queryInterface, Sequelize) {
await queryInterface.dropTable('addresses');
}
};
Please what am I doing wrong?
JS error on a flip-flop min max algorithm, the algorithm plays twice
I am writing this program to play tic-tac-toe against an algorithm, it uses the terminal as interface. When giving an input sequence, the program does two moves at once.
the part of code I think has a problem is in BIG:
function game(roundsNr){
console.log("insert the number of rounds you want to play");
roundsNr = getinput2();
let player = getplayer();
let Rwinner = "";
let playerWins = 0;
let algorithmWins = 0;
let playerturn = 0;
let algorithmsturn = 0;
if (player === "X"){
for (let i = 0; i < roundsNr; i++){
console.log("new round!")
console.log("fields are numbered like this: n 0 1 2 n 3 4 5 n 6 7 8");
if (playerturn <= algorithmsturn){
stand = startPos;
Rwinner = turn(startPos, "X");
playerturn++;
}
else{
**stand = startPos;
Rwinner = turn2(startPos, "X");
algorithmsturn++;**
}
if (Rwinner === "X"){
playerWins++;
}
else if (Rwinner == "O"){
algorithmWins++;
}
}
}
else if(player === "O"){
for (let i = 0; i <= roundsNr; i++) {
console.log("new round!")
console.log("fields are numbered like this: n 0 1 2 n 3 4 5 n 6 7 8");
if (playerturn <= algorithmsturn){
stand = startPos;
Rwinner = turn(startPos, "O");
playerturn++;
}
else{
stand= startPos;
Rwinner = turn2(startPos, "O");
algorithmsturn++;
}
if (Rwinner === "O"){
playerWins++;
}
else if (Rwinner == "X"){
algorithmWins++;
}
}
}
//cheking and outputting the final winner
if (playerWins > algorithmWins){
console.log("you have won and asserted your dominance over THE ALGORITHM")
}
else if (playerWins < algorithmWins){
console.log("THE ALGORITHM has defied you and will come for more, fear human")
}
else if (playerWins = algorithmWins){
console.log("beware! the Algorithm is as smart (or dumb) as you!")
}
}
When the player X is chosen and roundsNR
is bigger than 2 (I use 3), by the second round the algorithm moves 2 times, for itself and for me and then asks me to move
The purpose of the if loop, is to execute a flip flop for who starts playing (turn (me)/ turn2 (algorithm))
for the requested number of rounds (roundsNr)
, switching between who starts.
When executed out of the game()
function, it works perfectly, the problem is when it is the second turn, maybe I didn’t reset a variable.
Is it possible to change the color of individual splitlines in Apache ECharts for React gauge chart?
I have a gauge chart where the progress bar indicator goes from 0 to 180 degrees, similarly to this example.
What I want to do is have the splitline colors follow the color of progress bar. For instance, if the progress bar and pointer are at 50%, all splitlines until that point should be the same color as the progress bar, while the rest should be a default color.
I know that I can set options for the chart, however this only allows me to set the color of splitlines as a who. Is there a way to access them individually and color them based on some condition?
I’ve already tried providing a callback function that takes the value of the progress bar, but it seems like it doesn’t work – all splitlines are then colored black, which I guess is a fallback color.
Javascript inside HTML not working in Angular
I have JavaScript for my navbar under my HTML which is to close and open the navbar. However, none of the functions work for javascript. Please help me how I can fix this to make it work.
I have tried script under html and also tried putting my javascript under assets. However, I do not know how to call that file from my navbar.component.ts file.
JavaScript:
`<script>
let arrow = document.querySelectorAll(".arrow");
console.log(arrow);
for (var i = 0; i < arrow.length; i++) {
arrow[i].addEventListener("click", (e) => {
let arrowParent = e.target.parentElement.parentElement;
arrowParent.classList.toggle("showMenu");
});
}
let sidebar = document.querySelector(".sidebar");
let sidebarBtn = document.querySelector(".bx-menu");
sidebarBtn.addEventListener("click", () => {
sidebar.classList.toggle("close");
});
</script>
`
I want the images on my page to be clicked as many times as I want
There are 3 images on my index page. I want the images to be clicked as much as the value I get from the input, but it goes into an endless loop in the code I wrote.
inputField.addEventListener("keyup",(e)=>{
let inputVal=inputField.value;
if(e.key=="Enter" && inputVal.length > 0){
inputField.value="";
let i=0;
while(i<inputVal){
for (const image of optionImages) {
image.addEventListener("click",()=>{
i++;
})
}
console.log(i);
}
}
});