Category: javascript
Category Added in a WPeMatico Campaign
How do I make my function not need a reload to run time correctly [closed]
Essentially I have a button on my website and I need to refresh it to have the time update.
Its a minor problem but is there a way to fix it, so less time is needed to be used?
So I’m curious to how I make it not need a refresh to run heres the code for it.
var timeLeft;
var startTime = 8.47;
var date = new Date();
var currentTime = date.getHours() + date.getMinutes() / 100;
//var IsWeekend = date.getDay;
var endOfAdvisory = 9.11;
var endOfSecond = 9.57;
var endOfThird = 10.48;
var endOfFourth = 11.39;
var endOfFifth = 12.3;
var endOfLunch = 13.05;
var endOfSixth = 13.56;
var endOfSeventh = 14.47;
var endOfEigth = 15.4;
var endOfSchool = 15.4;
var schoolActive = null;
function tellTime() {
if (timeLeft >= 1) {
// to fixed rounds decimals
alert("There is: " + timeLeft.toFixed(2) + " hours(s) left");
} else if (timeLeft < 1) {
alert("There is: " + timeLeft.toFixed(2) + " minute(s) left");
}
}
// is school active / has it started
if (currentTime >= startTime && currentTime < endOfSchool) {
schoolActive = schoolActive === null ? true : schoolActive;
} else if (currentTime > endOfSchool) {
schoolActive = schoolActive === null ? false : schoolActive;
} else {
console.log("How tf was this printed??");
}
function isAdvistory() {
if (currentTime >= startTime && currentTime < endOfAdvisory) {
alert("Your in advisory");
timeLeft = 9.11 - currentTime;
tellTime();
return;
}
}
function isSecond() {
if (currentTime >= endOfAdvisory && currentTime < endOfSecond) {
alert("Your in second period");
timeLeft = endOfSecond - currentTime;
tellTime();
return;
}
}
function isThird() {
if (currentTime >= endOfSecond && currentTime < endOfThird) {
alert("Your in third period");
timeLeft = endOfThird - currentTime;
tellTime();
return;
}
}
function isFourth() {
if (currentTime >= endOfThird && currentTime < endOfFourth) {
alert("Your in fourth period");
timeLeft = endOfFourth - currentTime;
tellTime();
return;
}
}
function isFifth() {
if (currentTime >= endOfFourth && currentTime < endOfFifth) {
alert("Your in fifth period");
timeLeft = endOfFifth - currentTime;
tellTime();
return;
}
}
function isLunch() {
if (currentTime >= endOfFifth && currentTime < endOfLunch) {
const easteregg = Math.floor(Math.random() * 100) + 1;
if (easteregg == 52) {
alert("Your in munchy munch time");
} else {
alert("Your at lunch");
}
timeLeft = endOfSixth - currentTime;
tellTime();
return;
}
}
function isSixth() {
if (currentTime >= endOfLunch && currentTime < endOfSixth) {
alert("Your in sixth period");
timeLeft = endOfSixth - currentTime;
tellTime();
return;
}
}
function isSeventh() {
if (currentTime >= endOfSixth && currentTime < endOfSeventh) {
alert("Your in seventh period");
timeLeft = endOfSeventh - currentTime;
tellTime();
return;
}
}
function isEigth() {
if (currentTime >= endOfSeventh && currentTime < endOfEigth) {
alert("Your in eight period");
timeLeft = endOfEigth - currentTime;
tellTime();
return;
}
}
function isSchoolOver() {
if (currentTime >= 15.4) {
alert("Schools has ended");
schoolActive = false;
return;
}
}
function findPeriod() {
isAdvistory();
isSecond();
isThird();
isFourth();
isFifth();
isLunch();
isSixth();
isSeventh();
isEigth();
isSchoolOver();
}
function schoolTimeCalc() {
if (schoolActive === true) {
findPeriod();
} else {
alert("Your not even in school");
}
}
I haven’t tried anything yet due to me being new to javascript
Non-functioning dropdown bar
I am very new to using javascript and i dont fully understand it yet. I tried making a drop down bar with this html containing of a nav bar with a div that has some anchor tags. The javascript is a function retrieving the anchor tags by class using querySelectorAll. And a let determining whether or not the dropdown menu is open. It will change the style depending on this. If its really bad code please tell me im very new to this.(https://i.stack.imgur.com/VO6sF.jpg)(https://i.stack.imgur.com/6iL1P.jpg)
The issue is that when i hover on the dropdown it goes down which is good. But when i leave it it doesnt go back up.
how to get result directly in javascript [closed]
I want get report status from td status directly. So, if user input the result then report status will update too from status.
if one of status get value fail then report status will get value fail too although one of status get value pass.
Here’s the javascript
<script>
function hitung_status()
{
var pass = document.querySelectorAll('[name="status_hidden[]"]')[0].value == 'pass';
var fail = document.querySelectorAll('[name="status_hidden[]"]')[0].value == 'fail';
if (fail >= 1){
document.querySelector('[name="result_status"]').value = 'fail';
console.log('fail');
}else{
document.querySelector('[name="result_status"]').value = 'pass';
console.log('pass');
}
}
</script>
Thank you
Hiding an element of a web page depending on the url
I am loading a form into a page via javascript and I only want to show this form when the url contains a specific expression like: /home.
The form loads for the main page and all sub pages and should only be shown for a sub page containing the above expression, while hidden for all other cases.
I am relatively new to javascript and this problem really strikes me, so any help would be welcome and greatly appreciated.
Best,
Christian
Any help to get started is welcome
Get User’s Country Based on Time Zone in JavaScript [closed]
I want to determine the user’s country based on their time zone in JavaScript without using any IP-to-location service (like maxmind, ipregistry or ip2location). The following code uses the moment-timezone library to map time zones to countries and returns either the matching country or the original time zone if no match is found.
// Import the moment-timezone library
const moment = require('moment-timezone');
/**
* Get the user's country based on their time zone.
* @param {string} userTimeZone - The user's time zone.
* @returns {string} The user's country or the original time zone if not found.
*/
function getCountryByTimeZone(userTimeZone) {
// Get a list of countries from moment-timezone
const countries = moment.tz.countries();
// Iterate through the countries and check if the time zone is associated with any country
for (const country of countries) {
const timeZones = moment.tz.zonesForCountry(country);
if (timeZones.includes(userTimeZone)) {
// Use Intl.DisplayNames to get the full country name
const countryName = new Intl.DisplayNames(['en'], { type: 'region' }).of(country);
return countryName;
}
}
// Return the original time zone if no matching country is found
return userTimeZone;
}
// Example usage
const userTimeZone = Intl.DateTimeFormat().resolvedOptions().timeZone;
const userCountry = getCountryByTimeZone(userTimeZone);
console.log('User country based on time zone:', userCountry);
Usage:
Copy and paste the provided code into your JavaScript environment.
Call the getCountryByTimeZone function with the user’s time zone to retrieve the user’s country.
The function returns either the matching country or the original time zone if no match is found.
Note:
Make sure to have the moment-timezone library installed in your project.
The accuracy of the result depends on the completeness and accuracy of the time zone data provided by the library.
How to pass dictionary values from jinaja template to javascript
I need to display a size drop down in jinja template and on change of option, I want to display an image from the dictionary. I am passing the entire dictionary to a javascript function but getting the value by key in js file returns individual characters rather than value. It appears js function is not treating result as dictionary. Any help regarding this would be greatly appreciated.
<div class="single-product-form">
<form action="index.html">
<label for="size">Choose size</label>
<select name="colours" onchange="displayTryImg(this)">
{% for sizekey, sizevalue in product.sizes.items() %}
<option value="{{ sizevalue }}" SELECTED>{{ sizevalue.product_size }}</option>
{% endfor %}
</select>
<div class="tray-image"><img id="tray-img" src=""></div>
</form>
</div>
Java script function looks like this
function displayTryImg(size){
var result = size.value;
console.log('result '+result)
for(var key in result){
console.log('val : '+result[key]) // This prints individual characters rather
}
document.getElementById("tray-img").src="/static/images/"+result['size_image']; // undefined
}
Console log output
result {'size_id': 3, 'product_size': 'Medium Tray', 'product_quantity': 2, 'size_description': 'Medium Tray usually enough for 3 people', 'size_image': 'tray.jpg'}
custom.js:76 val : {
custom.js:76 val : '
custom.js:76 val : s
custom.js:76 val : i
custom.js:76 val : z
custom.js:76 val : e
custom.js:76 val : _
custom.js:76 val : i
custom.js:76 val : d
custom.js:76 val : '
custom.js:76 val : :
custom.js:76 val :
custom.js:76 val : 3
custom.js:76 val : ,
custom.js:76 val :
custom.js:76 val : '
custom.js:76 val : p
custom.js:76 val : r
custom.js:76 val : o
custom.js:76 val : d
custom.js:76 val : u
custom.js:76 val : c
custom.js:76 val : t
custom.js:76 val : _
custom.js:76 val : s
custom.js:76 val : i
custom.js:76 val : z
custom.js:76 val : e
custom.js:76 val : '
custom.js:76 val : :
custom.js:76 val :
custom.js:76 val : '
custom.js:76 val : M
custom.js:76 val : e
custom.js:76 val : d
custom.js:76 val : i
custom.js:76 val : u
custom.js:76 val : m
custom.js:76 val :
custom.js:76 val : T
custom.js:76 val : r
custom.js:76 val : a
custom.js:76 val : y
custom.js:76 val : '
custom.js:76 val : ,
custom.js:76 val :
custom.js:76 val : '
custom.js:76 val : p
custom.js:76 val : r
custom.js:76 val : o
custom.js:76 val : d
custom.js:76 val : u
custom.js:76 val : c
custom.js:76 val : t
custom.js:76 val : _
custom.js:76 val : q
custom.js:76 val : u
custom.js:76 val : a
custom.js:76 val : n
custom.js:76 val : t
custom.js:76 val : i
custom.js:76 val : t
custom.js:76 val : y
custom.js:76 val : '
custom.js:76 val : :
custom.js:76 val :
custom.js:76 val : 2
custom.js:76 val : ,
custom.js:76 val :
custom.js:76 val : '
custom.js:76 val : s
custom.js:76 val : i
custom.js:76 val : z
custom.js:76 val : e
custom.js:76 val : _
custom.js:76 val : d
custom.js:76 val : e
custom.js:76 val : s
custom.js:76 val : c
custom.js:76 val : r
custom.js:76 val : i
custom.js:76 val : p
custom.js:76 val : t
custom.js:76 val : i
custom.js:76 val : o
custom.js:76 val : n
custom.js:76 val : '
custom.js:76 val : :
custom.js:76 val :
custom.js:76 val : '
custom.js:76 val : M
custom.js:76 val : e
custom.js:76 val : d
custom.js:76 val : i
custom.js:76 val : u
custom.js:76 val : m
custom.js:76 val :
custom.js:76 val : T
custom.js:76 val : r
custom.js:76 val : a
custom.js:76 val : y
custom.js:76 val :
custom.js:76 val : u
custom.js:76 val : s
custom.js:76 val : u
custom.js:76 val : a
2custom.js:76 val : l
custom.js:76 val : y
custom.js:76 val :
custom.js:76 val : e
custom.js:76 val : n
custom.js:76 val : o
custom.js:76 val : u
custom.js:76 val : g
custom.js:76 val : h
custom.js:76 val :
custom.js:76 val : f
custom.js:76 val : o
custom.js:76 val : r
custom.js:76 val :
custom.js:76 val : 3
custom.js:76 val :
custom.js:76 val : p
custom.js:76 val : e
custom.js:76 val : o
custom.js:76 val : p
custom.js:76 val : l
custom.js:76 val : e
custom.js:76 val : '
custom.js:76 val : ,
custom.js:76 val :
custom.js:76 val : '
custom.js:76 val : s
custom.js:76 val : i
custom.js:76 val : z
custom.js:76 val : e
custom.js:76 val : _
custom.js:76 val : i
custom.js:76 val : m
custom.js:76 val : a
custom.js:76 val : g
custom.js:76 val : e
custom.js:76 val : '
custom.js:76 val : :
custom.js:76 val :
custom.js:76 val : '
custom.js:76 val : t
custom.js:76 val : r
custom.js:76 val : a
custom.js:76 val : y
custom.js:76 val : .
custom.js:76 val : j
custom.js:76 val : p
custom.js:76 val : g
custom.js:76 val : '
custom.js:76 val : }
:8000/static/images/undefined:1
GET http://localhost:8000/static/images/undefined 404 (NOT FOUND)
How extracting a finger print from users using JavaScript [closed]
Hi I want to extract finger print frim user so I can store it the data bas if u can help me with just extracting the finger print and log it into the console that would be good and thank u
I didn’t come near to a solution but I want it cuz am building a ERP system
In the React.js context element is reset on every redirect
When you log in, there is no problem on the page entered with the first redirect. According to the console logs, the context is full. However, when you click on any page using the “Navbar”, the data received with the context returns null, and you are redirected to the Login page. I do not provide any method that will reset the data in the context. But I don’t understand why it resets.
Not: For session control, the isEnable variable in the context is checked.
index.js =>
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(
<React.StrictMode>
<UserProvider>
<BrowserRouter>
<App />
</BrowserRouter>
</UserProvider>
</React.StrictMode>
);
app.js =>
function App() {
const { contextUser } = useContext(UserContext);
const theme = createTheme({
palette: {
background: {
default: '#gray', // Background color of the app
},
},
});
return (
<>
<Navbar/>{/* Router in the Navbar */}
<Routes>
{contextUser.isEnable? (
<>
<Route path={"/"} element={<PatientQuery key={10}/>}/>
<Route path={"/Rapor_Sorgulama"} element={<PatientQuery key={10}/>}/>
<Route path={"/Hasta_Listesi"} element={<PatientList key={11}/>}/>
<Route path={"/Rapor_Tanımlama"} element={<ReportDefine key={12}/>}/>
<Route path={"/Tüm_Raporlar"} element={<AllReports key={13}/>}/>
<Route path="/MASTER" element={<Master/>} />
<Route path="*" element={<ErrorPage/>} />
</>
) : (
<>
<Route path={"/"} element={<PatientQuery key={10}/>}/>
<Route path="/Rapor_Sorgulama" element={<PatientQuery key={1}/>} />
<Route path="/Hasta_Listesi" element={<Login key={2}/>} />
<Route path="/Rapor_Tanımlama" element={<Login key={3}/>}/>
<Route path="/Tüm_Raporlar" element={<Login key={4}/>}/>
<Route path="/Login" element={<Login key={5}/>}/>
<Route path="/SignUp" element={<SignUp key={6}/>}/>
<Route path="*" element={<ErrorPage key={7}/>}/>
{/* <Navigate to="/error" /> */}
</>
)}
{/*
my_pages.map((page,index) => (
<Route path={`/${page}`} element={components[index]}/>
))
*/}
</Routes>
</>
);
}
export default App;
context/Context.js =>
import React, { createContext, useContext, useState } from 'react';
// User Authentication Context
export const UserContext = createContext();
export function UserProvider({ children }) {
const [contextUser, setContextUser] = useState({
fullName: "",
email: "",
token: "",
image: null,
authorities: [],
isEnable: null
});
const logIn = (userData) => {
setContextUser({
fullName: userData.user.fullName,
email: userData.user.email,
token: userData.token,
image: null,
authorities: userData.user.authorities,
isEnable: true
});
logContext()
};
const logContext = function () {
console.log(contextUser)
};
const logOut = () => {
setContextUser({
fullName: "deleted",
email: "",
token: "",
image: null,
authorities: [""],
isEnable: false
});
};
return (
<UserContext.Provider value={{ contextUser, logIn, logContext }}>
{children}
</UserContext.Provider>
);
}
Navbar.js =>
export default function Navbar() {
const my_pages = ['Rapor_Sorgulama', 'Hasta_Listesi', 'Rapor_Tanımlama', 'Tüm_Raporlar'];
const components = [
<PatientQuery key={my_pages[0]}></PatientQuery>,
<PatientList key={my_pages[1]}></PatientList>,
<ReportDefine key={my_pages[2]}></ReportDefine>,
<AllReports key={my_pages[3]}></AllReports>,
<Login key={5}></Login>,
<SignUp key={6}></SignUp>,
];
const { contextUser } = useContext(UserContext);
console.log("contextUser: ")
console.log(contextUser)
const my_settings = ['Profil', 'Hesap', 'Çıkış'];
const [anchorElUser, setAnchorElUser] = useState(null);
const handleOpenSettingsMenu = (event) => {
setAnchorElUser(event.currentTarget);
};
const handleCloseSettingsMenu = () => {
setAnchorElUser(null);
};
const myTheme = createTheme({
palette: {
mode: 'dark',
primary: {
main: '#002092',
}, secondary: {
main: '#002092',
},
},
});
return (
<>
<ThemeProvider theme={myTheme}>
<AppBar position="static" style={{ backgroundColor: '#002090' }}>
<Toolbar>
<ScienceTwoToneIcon></ScienceTwoToneIcon>
<Typography
variant="h5"
noWrap
component="a"
href="/"
sx={{
mr: 2,
fontWeight: 200,
fontFamily: 'roboto',
color: 'white',
letterSpacing: '.2rem',
textDecoration: 'none',
}}
>
LABREPORT
</Typography>
<Box sx={{ flexWrap: 'wrap', flexGrow: 1, display: 'flex' }}>
{my_pages.map((page) => (
<Button
key={my_pages}
sx={{ my: 2, color: 'whitesmoke', display: 'block', paddingRight: '20px' }}
href={`/${page}`}
>
{page}
</Button>
))}
</Box>
<Box sx={{ flexWrap: 'wrap', flexGrow: 1, display: 'flex' }}>
{
(contextUser.isEnable)? (null) : (
<>
<Button
sx={{ my: 2, color: 'whitesmoke', display: 'block', paddingRight: '15px' }}
href={`/login`}
>
Login
</Button>
<Button
sx={{ my: 2, color: 'whitesmoke', display: 'block', paddingRight: '15px' }}
href={`/SignUp`}
>
SignUp
</Button>
</>
)
}
{
// !(contextUser.authorities[0] === "ROLE_MASTER") ? (null) : (
!(contextUser.authorities[0] === "ROLE_MASTER" && contextUser.authorities != null) ? (null) : (
<>
<Button
sx={{ my: 2, color: 'tomato', display: 'block', paddingRight: '20px' }}
href={`/MASTER`}
>
MASTER
</Button>
</>
)
}
</Box>
<Box sx={{ flexGrow: 0 }}>
<Tooltip title="Open my_settings">
<IconButton onClick={handleOpenSettingsMenu} sx={{ p: 0 }}>
<Avatar alt="" src="" />
</IconButton>
</Tooltip>
<Menu
sx={{ mt: '55px' }}
id="menu-appbar"
anchorEl={anchorElUser}
anchorOrigin={{
vertical: 'top',
horizontal: 'right',
}}
open={Boolean(anchorElUser)}
onClose={handleCloseSettingsMenu}
>
{my_settings.map((setting) => (
<MenuItem key={setting} onClick={handleCloseSettingsMenu}>
<Typography textAlign="center">{setting}</Typography>
</MenuItem>
))}
</Menu>
</Box>
</Toolbar>
</AppBar>
</ThemeProvider>
</>
);
}
Login.js =>
export default function Login() {
const [user,setUser] = useState({
email: "error",
password: 'error',
})
const { contextUser, logIn, logOut } = useContext(UserContext);
const handleSubmit = (event) => {
// event.preventDefault();
// const data = new FormData(user.email,user.password);
fetch('/auth/login', {//AuthRequest is Object
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify([user.email,user.password])
})
.then(res => {//res={user:{k:v}, token:""}
if (res.ok) return res.json();
else alert("Giriş Başarısız");
throw new Error('Network response was not ok.');
})
// .then(res => logIn(res.user))
.then(res =>logIn(res))
.then(console.log(contextUser.user))
.catch(err => console.log(err.message));
};
return (
<ThemeProvider theme={defaultTheme}>
<Container component="main" maxWidth="xs" sx={{ backgroundColor: 'yourBackgroundColor' }}>
<CssBaseline />
<Box
sx={{
marginTop: 8,
display: 'flex',
flexDirection: 'column',
alignItems: 'center',
}}
>
<Avatar sx={{ m: 1, bgcolor: 'secondary.main' }}>
<LockOutlinedIcon />
</Avatar>
<Typography component="h1" variant="h5">
Teknisyen Girişi
</Typography>
<Box noValidate sx={{ mt: 1 }}>
{/* component="form" onSubmit={handleSubmit} */}
<TextField
margin="normal"
required
fullWidth
id="email"
label="Email Adresi"
name="email"
autoComplete="email"
autoFocus
onChange = {(e) => setUser({...user, email: e.target.value})}
/>
<TextField
margin="normal"
required
fullWidth
name="password"
label="Şifre"
type="password"
id="password"
autoComplete="current-password"
onChange = {(e) => setUser({...user, password: e.target.value})}
/>
<Button
type="submit"
fullWidth
variant="contained"
onClick={handleSubmit}
sx={{ mt: 3, mb: 2 }}
>
Giriş Yap
</Button>
<Grid container>
<Grid item xs>
<Link href="#" variant="body2">
Şifreni hatırlamıyor musun?
</Link>
</Grid>
<Grid item>
<Link href={"/SignUp"} variant="body2">
{"Yeni misin?"}
</Link>
</Grid>
</Grid>
</Box>
</Box>
<Copyright sx={{ mt: 8, mb: 4 }} />
</Container>
</ThemeProvider>
);
}
Could it be wrong that navbar buttons use “href={/${page}}”? I think “context.js” was re-rendered between redirects. But I dont have idea for the solution.
How to change the state of another reducer inside of the extraReducers?
Say I have the following lifecycle actions.
builder
.addCase(loginUser.pending, (state, action) => {
state.isLoading = true;
}).addCase(loginUser.fulfilled, (state, action) => {
state.isLoading = false;
state.user = action.payload;
// Change the Page to HomePage - using the location state from navigationSlice
toast.success('Logged In User!');
}).addCase(loginUser.rejected, (state, action) => {
state.isLoading = false;
toast.error(action.payload);
});
I want to invoke the setLocation reducer that changes the state value from the navigation reducer. Take a look.
import { createSlice } from '@reduxjs/toolkit';
import { getCurrentPageLocation } from '../../utils';
const initialState = {
location: getCurrentPageLocation()
};
const navigationSlice = createSlice({
name: 'navigation',
initialState,
reducers: {
setLocation: (state, action) => {
state.location = action.payload;
}
},
extraReducers: (builder) => {
}
});
export const { setLocation } = navigationSlice.actions;
export default navigationSlice.reducer;
How can I invoke the setLocation method inside of the extraReducers (loginUser.fulfilled)? Now I know I can just dispatch this using the thunkAPI in the createAsyncThunk but I don’t like doing that. I want to be able to invoke it straight from the extraReducers and preferably without importing anything.
Unity/Firestore Functions in JS: Invalid Type for conversion to variant – when passing a list of classes via a dictionary
I’m trying to create a cloud function written in JS that creates a new game.
I’m sending in a list of PlayerInfo from Unity, but every time I get an error about my data received as being an Invalid Type.
I’ve tried multiple different approaches from the C# Unity side but every time I get returned an error of either
1st approach
"Error creating game invite: Invalid type System.Collections.Generic.List System.Collections.Generic.Dictionary System.String,System.String for conversion to Variant"
2nd approach
"Invalid type PlayerInfo for conversion to Variant"
- code for 1st C# approach
public async void CallCreateGameInvite()
{
List Dictionary string, string players = new List
{
new Dictionary { { "username", "Player1" }, { "userID", "userID1" } },
new Dictionary { { "username", "Player2" }, { "userID", "userID2" } }
// Add additional players here
};
await CreateGameInvite(players);
}
private async Task CreateGameInvite(List<Dictionary<string, string>> players)
{
try
{
FirebaseFunctions functions = FirebaseFunctions.DefaultInstance;
var func = functions.GetHttpsCallable("createGameInvite");
var result = await func.CallAsync(new { players });
Debug.Log("Game invite created with ID: "); //result.Data["gameID"]);
// Use the gameID and perform further actions in your Unity project
}
catch (Exception e)
{
Debug.LogError("Error creating game invite: " + e.Message);
}
}
- code for 2nd C# approach
List players = new List
{
new PlayerInfo("Player1", "userID1"),
new PlayerInfo("Player2", "userID2"),
};
[System.Serializable]
public class PlayerInfo
{
public string username;
public string userID;
public PlayerInfo(string username, string userID)
{
this.username = username;
this.userID = userID;
}
}
private async void CreateGameInvite(List players)
{
try
{
var requestData = new Dictionary
{
{ "players", players }
};
FirebaseFunctions functions = FirebaseFunctions.DefaultInstance;
var func = functions.GetHttpsCallable("createGameInvite");
var result = await func.CallAsync(requestData);
Debug.Log("Game invite created with ID: " + result.Data);
// Use the gameID and perform further actions in your Unity project
}
catch (Exception e)
{
Debug.LogError("Error creating game invite: " + e.Message);
}
}
- Here is my code for the JS cloud function:
// Class for player information
class PlayerInfo
{
constructor(username, userID) {
this.username = username;
this.userID = userID;
}
}
exports.createGameInvite = functions.https.onCall(async (data, context) => {
try
{
const gameID = generateUniqueGameID();
// List of players
const players = data.players; // Assuming that players are passed in the request data
// Create a document in the Firestore collection named GameInvites
const gameInviteRef = admin.firestore().collection('GameInvites').doc(gameID);
await gameInviteRef.set({ players: players });
// Add the game invite to UserGameInvites collection for each user ID
players.forEach(player => { admin.firestore().collection('UserGameInvites').doc(player.userID).collection('invites').doc(gameID).set({ gameID: gameID });
});
return { gameID: gameID }; // Return the gameID as the result
} catch (error) {
throw new functions.https.HttpsError('internal', 'Error creating game invite', error);
}
});
I’m guessing I’m missing something about how parse the ‘data’ object in the JS I’m sending from Unity.
Would very much appreciate any help!(:
How do I display an array that I have created in NodeJS in HTML?
Ok, so I am fairly new to this stuff so I’ll try to be as cohesive as I can with my problem.
I have created a simple web scraper using NodeJS, Express and Axios. This web scraper scrapes text from a class on a defined URL and passes the results in the console as a string using JSON.stringify.
The problem I am having, is I cannot work out a way to display this array text on a HTML page in a p tag.
For now, I have removed the URL and classnames as I want to keep what I am doing fairly low key, but I have replaced it with uppercase text. The MY URL GOES HERE is the URL of the site I am scraping from, and the CLASSNAME is the name of the specific class I am pulling text from.
Node JS index.js file:
const axios = require('axios')
const cheerio = require('cheerio')
const express = require('express')
const app = express()
const url = 'MY URL GOES HERE'
app.use('/', express.static('index.html'))
axios(url)
.then(response => {
const html = response.data
const $ = cheerio.load(html)
const textArray = []
$('.CLASSNAME', html).each(function() {
const myTextArray = $(this).text()
textArray.push({
myTextArray
})
})
const finalResult = JSON.stringify(textArray)
console.log(finalResult)
}).catch(err => console.log(err))
app.listen(PORT, () => console.log(`Server running on ${PORT}`))
index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
<script src="index.js"></script>
</head>
<body>
<h1 class="headline">This is the ingredients list</h1>
<p class="array"></p>
<script>
var results = document.getElementsByClassName('array')
console.log(results)
</script>
</body>
</html>
I am not sure how to get the array from the NodeJS js file and show it within the p tag within my HTML file.
I tried to install Puppeteer as I read this allows NodeJS to use standard JS commands in the DOM but I was getting these errors:
npm ERR! code EEXIST
npm ERR! syscall mkdir
npm ERR! path /Users/MYNAME/.npm/_cacache/content-v2/sha512/88/53
npm ERR! errno EEXIST
npm ERR! Invalid response body while trying to fetch https://registry.npmjs.org/js-yaml: EACCES: permission denied, mkdir '/Users/MYNAME/.npm/_cacache/content-v2/sha512/88/53'
npm ERR! File exists: /Users/MYNAME/.npm/_cacache/content-v2/sha512/88/53
npm ERR! Remove the existing file and try again, or run npm
npm ERR! with --force to overwrite files recklessly.
npm ERR! A complete log of this run can be found in: /Users/MYNAME/.npm/_logs/2023-12-15T01_00_27_889Z-debug-0.log
I am very new to this, so if I have missed anything or you need any extra context please let me know and I’ll do my best to provide information where I can.
My onclick attribute is not finding the function within the imported javascript
I’ve made a function that accepts an id then reveals the element associated with that id. I want this function to be used for the html attribute onclick, but I have been having problems with it not being able to find the function returning the error below when clicked on.
And this is how the onclick attribute look
<button onclick="revealOnClick('SomeTypeofID')"><a style="font-size: 4vw;">Sometype of Button<a></button>
The function is within a javascript file
export function revealOnClick (id = '') { document.getElementById("id").style.removeProperty("display"); }
that is imported into another javascript file
import {Panel, revealOnClick} from "./JS_Module/websitemodule.js";
then I import the javascript file into the html
<script defer type="module" src="index.js"></script>
However it still seems to not be able to find it.
I’ve tried moving around the <script defer type="module" src="index.js"></script>, it ‘s currently on top in the head, but I’ve removed the “defer” and put it at the bottom below the head, thinking it wasn’t able to laod the javascript, but that didnt work.
I’ve tried moving the code below into the javascript file it was importing to and removed the export, but that also didn’t work.
export function revealOnClick (id = '') { document.getElementById("id").style.removeProperty("display"); }
I’ve also tried adding the type="button" thinking it could be the submit and then after I’ve tried moving the onclick to the anchor tag, but both didn’t work
<button><a style="font-size: 4vw;" onclick="revealOnClick('SomeTypeofID')">Sometype of Button<a></button>
highchart column chart compare with arrow
I tried to make a compare chart.
I’ve read the highchart document many times and searched hard, but I couldn’t find an option to create the chart I wanted.
This is the original chart.
//chart1
Highcharts.chart('chart1', {
chart: {
type: 'column',
},
title: {
text: 'Compare chart',
},
subtitle: null,
xAxis: {
categories: ['before', 'after', ],
},
yAxis: [{
title: {
text: 'title1'
},
}, {
title: {
text: 'title2'
},
opposite: true,
}, ],
series: [{
name: 'series1',
color: '#f5b93d',
data: [8652, 4321],
}, {
name: 'series2',
color: '#42a7f4',
data: [100, 50],
yAxis: 1,
} ]
});
full source : https://jsfiddle.net/publisherkim/m6g87hkf/10/
and This is what I want to make.
https://umings.github.io/images/tobe.png
I would like to indicate how much the data of series1 has been reduced to before and after in this way.
If anyone has seen a similar format chart, or knows any options, please help. Thanks.
Buttons with JavaScript do not work in the form
My problem is that I have a form in my HTML that I write to the database after filling it out.
The form consists of 7 labels with 7 input fields type=’number’
It all works so far, but it annoys me because it is designed for mobile phones that I have to keep clicking on the field and entering the number.
Now I have come up with a system that I can use between the input fields type=’text’,
I have one button each for increase and decrease. I intercept this with a JavaScript and let the will be manipulated to correspond.
This only worked to a limited extent. If I comment out the “Form Tag” it works. But as soon as I comment on the “form tag” again, nothing works anymore.
Now the question is. Where is the mistake or why it no longer works in this form?
HTML excerpt:
<form action="" method="post">
<label>Test1</label><br>
<input type="button" onclick="dec('number')" id="dec" value="-"/>
<input type="text" name="test1" id="number" value="0" min="0" size="3" />
<input type="button" onclick="inc('number')" id="inc" value="+" />
</form>
JS excerpt:
function inc(number) {
document.getElementById("number").value++;
}
function dec(number) {
if (document.getElementById("number").value != 0)
document.getElementById("number").value--;
}
