Category: javascript
Category Added in a WPeMatico Campaign
How to change to the next object in an array in javascript based on the date changing – how to change to the next word of the day
I have very little experience with coding and I’ve never asked a question on here so please bear with me. I am trying to make a “word of the day” generator with html, css, and javascript specifically (please no other languages if possible), for my website. My site is hosted on one of those drag-and-drop website builders that lets you put a few lines of html code in a block. I used an AI code generator to get this javascript, and instead of changing the word each day it chose to use the randomize function. So every time I reload my website page, the function spits out a random word/definition from the array. I would like to move to the next word/definition in the array every time the day changes. I don’t even mind if it chooses a new random word from the array instead of just moving to the next object, as long as it only changes once a day and not each time you load it.
And I do want to fill it with my own words and definitions rather than pull from and API. It just makes things simpler for me if I want to change something around later, and copy it to other types of apps I’m trying to make.
Oh, and using “wordo” instead of “word”, and “definitiono” instead of “definition” was entirely purposeful. I have other things like a searchable dictionary and an actual word generator on the same webpage that I’m trying to put this on, and when different elements get called the same thing it gets screwy really fast so that was my fix. Keeping the words in the word container is also intentional, it just goes with the styling on my site.
Here’s my code:
<!DOCTYPE html>
<html>
<head>
<style>
.word-container {
width: 80%;
outline: none;
font-size: 16px;
border-radius: 5px;
padding-left: 15px;
padding-right: 27px;
border: 1px solid #999;
}
</style>
</head>
<body>
<div class="word-container">
<h2 id="wordo"></h2>
<p id="definitiono"></p>
</div>
<script>
const wordos = [
{
wordo: "Abstemious",
definitiono:
"sparing or moderate in eating and drinking; temperate in diet",
},
{
wordo: "Bellicose",
definitiono: "demonstrating aggression and willingness to fight",
},
{
wordo: "Tawdry",
definitiono:
"showy but cheap and of poor quality; sordid or unpleasant",
},
];
{
const wordoOfTheDay = wordos[Math.floor(Math.random() * wordos.length)];
const wordoEl = document.getElementById("wordo");
const definitionoEl = document.getElementById("definitiono");
wordoEl.textContent = wordoOfTheDay.wordo;
definitionoEl.textContent = wordoOfTheDay.definitiono;
}
</script>
</body>
</html>
Async function returns a not empty array but length = 0 [duplicate]
I have this JavaScript code:
function Static (subject, quantity){
this.subject = subject
this.quantity = quantity
}
async function get_statics(subjects) {
let total = []
subjects.forEach(async subject => {
let questions = []
let response = await fetch("/api/filter_question", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
User: {
id: 0,
subject: subject,
level: 0,
start_date: "1970-06-01T14:55:47.530641212",
end_date: "2999-04-14T14:55:47.530641212",
creator: 2,
verified: true
}
})
})
if (!response.ok) {
window.location = "/?status=questionModifyError"
}
else {
questions.push((await response.json()).length)
}
response = await fetch("/api/filter_question", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
User: {
id: 0,
subject: subject,
level: 1,
start_date: "1970-06-01T14:55:47.530641212",
end_date: "2999-04-14T14:55:47.530641212",
creator: 2,
verified: true
}
})
})
if (!response.ok) {
window.location = "/?status=questionModifyError"
}
else {
questions.push((await response.json()).length)
}
response = await fetch("/api/filter_question", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
User: {
id: 0,
subject: subject,
level: 2,
start_date: "1970-06-01T14:55:47.530641212",
end_date: "2999-04-14T14:55:47.530641212",
creator: 2,
verified: true
}
})
})
if (!response.ok) {
window.location = "/?status=questionModifyError"
}
else {
questions.push((await response.json()).length)
}
response = await fetch("/api/filter_question", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
User: {
id: 0,
subject: subject,
level: 3,
start_date: "1970-06-01T14:55:47.530641212",
end_date: "2999-04-14T14:55:47.530641212",
creator: 2,
verified: true
}
})
})
if (!response.ok) {
window.location = "/?status=questionModifyError"
}
else {
questions.push((await response.json()).length)
}
response = await fetch("/api/filter_question", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
User: {
id: 0,
subject: subject,
level: 4,
start_date: "1970-06-01T14:55:47.530641212",
end_date: "2999-04-14T14:55:47.530641212",
creator: 2,
verified: true
}
})
})
if (!response.ok) {
window.location = "/?status=questionModifyError"
}
else {
questions.push((await response.json()).length)
}
response = await fetch("/api/filter_question", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
User: {
id: 0,
subject: subject,
level: 5,
start_date: "1970-06-01T14:55:47.530641212",
end_date: "2999-04-14T14:55:47.530641212",
creator: 2,
verified: true
}
})
})
if (!response.ok) {
window.location = "/?status=questionModifyError"
}
else {
questions.push((await response.json()).length)
}
total.push(new Static(subject, questions))
})
return total
}
async function get_global_statics(subjects) {
let data = await get_statics(subjects)
console.log(data)
}
The use of this is to create an array of this kind [Static{“subject”, [0, 0, 0, 1}], …
The array is Ok it has got data, and also I can print it in the console. But when I try to access to an element or getting the length I get undefined.
I think that this happen because the value is shown before promise resolved.
Full code at text
I tried many things related to async. I expect to get some data when reading the array.
Am trying to get json data success response but i got error
please help me I am a junior my code is not good I need to get a JSON response for each successfully sent message. I can send the SMS successfully but I can’t get a success message from send_sms.php
<!-- index.php --->
<div id="responce"></div> <!-- respond sms sending -->
<form method="POST" onclick="return false">
<div class="form-group">
<label>Your Message</label>
<textarea class="form-control" rows="4" cols="100" id="message"
name="message" maxlength="70" required></textarea>
</div>
<button class="btn btn-primary" type="submit" name="submit"
onmousedown="start_sendig();" class="btn">Send</button>
</form>
//sendsms_button.js
function start_sendig() {
$("#responce").html("Please wait sending on process");
var message = $("#message").val();
var path_uri = "sms/send_sms.php";
$.ajax({
type: "POST",
url: path_uri,
data: {
message: message,
},
success: function (data) {
var json = $.parseJSON(data);
if (json.response == "success") {
$("#responce").html(
"Message Sent Successfully to " + json.current + " !!"
);
} else {
$("#responce").html("Error to Sent " + json.current + " !!");
}
},
});
}
Ajax shows this error
caught SyntaxError: Unexpected end of JSON input
at Function.parse [as parseJSON] (<anonymous>)
at Object.success (sendsms_button.js:13:20)
at i (jquery-3.2.1.min.js:2:28017)
at Object.fireWith [as resolveWith] (jquery-3.2.1.min.js:2:28783)
at A (jquery-3.2.1.min.js:4:14035)
at XMLHttpRequest.<anonymous> (jquery-3.2.1.min.js:4:16323)
<?php
//send_sms.php
include ("vendor/autoload.php");
include ("../config.php");
//insert record
$msg_sms = $_POST['message'];
mysqli_query ($con, "insert into sent_sms (message) values ('$msg_sms')");
if (isset($_POST['submit'])){
//select numbers
$result = mysqli_query($con, "SELECT mphone FROM members");
while ($row = mysqli_fetch_array($result)){
$numbers = $row['mphone'];
foreach (explode("+", $numbers) as $phone) {
$basic = new VonageClientCredentialsBasic("fxxxxx", "xxxxxxxxxxxxx");
$client = new VonageClient($basic);
$response = $client->sms()->send(
new VonageSMSMessageSMS($phone, 'Hotel', $msg_sms)
);
$message = $response->current();
if ($message->getStatus() == 0) {
$data = array(
"response" => "success",
"current" => '+' . $phone
);
echo json_encode($data);
} else {
echo "<script>alert('The message failed with status: " . $message->getStatus() . "');</script>";
}
}
}
}
?>
my goal is to show each success message like Sending to +125332626 success
How to restore Scroll position in react?
I am currently using version 6 and I cannot find any modern solution to this one. Since the previous tutorial are using old Browse router version.
import Navbar from './components/Navbar';
import Home from './Home';
import MovieDetails from './components/MovieDetails';
import Footer from './components/Footer';
import { BrowserRouter as Router, Route, Routes } from 'react-router-dom';
import data from './data/data'
import './App.css';
function App() {
return (
<Router>
<div className="App">
<Navbar></Navbar>
<Routes>
<Route exact path='/' element={<Home></Home>} ></Route>
<Route path='/movies/:id' element={<MovieDetails ></MovieDetails>} ></Route>
</Routes>
<Footer></Footer>
</div>
</Router>
);
}
export default App;
what would be the best way to fix this issue every time I click on a link it keeps its position on the page.
Insert every array item into Mysql database using react js
I fetched my api and inserted the data into array.
And then I tried to insert every item in array into Mysql database.
But execution of code only return 3 items not 20 items(length of array).
My code is below:
const label = [];
const calories = [];
const getData = async () => {
const response = await axios.get(
`https://api.edamam.com/api/recipes/v2?type=public&q=egg&app_id=${APP_ID}&app_key=${APP_KEY}`
);
const data = response.data.hits;
data.map((item) => {
label.push(item.recipe.label); //label object in api
calories.push(item.recipe.calories); //calories object in api
});
app.post("/books", (req, res) => {
for (var i = 0; i < label.length; i++) {
const q = "INSERT INTO apiData (`name`, `calories`) VALUES (?)";
var values = [label[i], calories[i]];
db.query(q, [values], (err, data) => {
if (err) return res.json(err);
return res.json("Data created successfully!");
});
}
});
};
getData();
I’m using postman to post into mysql.
When I click send button in POST mode, it returns below
return image
If anyone knows what’s the problem please let me know
THank you
Trying to write to a external json file using fs and express
I’m trying to write an object to a JSON, when passing the data through to the server I keep receiving this error and I cannot seem to find a solution to fix it…
Here is my code
APP.post('/api', (req, res) => {
const data = req.body;
console.log(data);
try {
fs.writeFileSync(PATH, data);
} catch(err) {
console.log(err)
}
res.send("Updated");
});
The object looks like the following i.e. req.body
{
name: '',
currentStats: {
stat: 0,
},
trackStats: { history: 0 }
}
The error in question
TypeError [ERR_INVALID_ARG_TYPE]: The "data" argument must be of type string or an instance of Buffer, TypedArray, or DataView. Received an instance of Object
Webpack files are not present in the extension folder, but they just appears when I’m using the extension, how to find them?
I’m trying to add a new feature to an already existing extension, but there is something wrong with that.
First of all when I’m actually using the extension and running devtools, I can see that here is also loaded the webpack page too , it doesnt exist in my source code folder, looks like it just loaded dynamically and the file I want to improve is located in this webpack page only.
When I’m trying to get the url of this file, I get this: webpack:///popup/index.tsx
There is no folder like that in the source code folder, idk where it is located and how to access it
I’m trying to just find it in my source code folder of the extension and do my modification to this app to use it how I need.
Vertical slider can’t be dragged to move on mobile
My first question ever so apologies in advance for anything incorrect or missing, I’m a total beginner.
I’m working on a mini JS/html app that includes a vertical slider (via transform:rotate) and on desktop, everything works fine, but on mobile (android, or chrome via device mode in developer tools) the thumb can’t be dragged.
It’s still possible to change the slider value by touching the slider track, but no longer possible to move the thumb by dragging. How can I get that working?
Here’s minimal code to show the problem. The app is vanilla JS, ideally a solution would also be vanilla if JS is needed.
<div id="slider-container">
<input type="range" min="0" max="100" value="10">
</div>
body {
text-align: center;
}
#slider-container {
transform: rotate(-90deg)
}
At first I thought it was because vertical dragging was triggering scroll behaviour, but it still happens even with overflow:hidden.
It must be something simple but I’m stumped after much googling…
how to get values of radio button
hi iam trying to get the values of the radio buttons from this page text and every time i get undefined or
caught TypeError: Cannot read properties of null (reading 'addEventListener')
this is the code i did for now
btn=document.querySelector(".buttonNext");
btn.addEventListener("click", function radio() {
selected=document.querySelector(".css-1crzc9r:checked");
console.log("selected");
});
if it get past to the btn.addeventlisetner i still has the problem of Undefined am i doing something wrong maybe select wrong class or something but i already tried all the classes and they all give me undefined
Trying to get react-native-calendars TimelineList working
I’m at a loss at this point. I’ve been trying for days to render my TimelineList calendar. For some reason the items are not showing up. My code is a little crazy at this point trying multiple things. If anyone has any thoughts I would appreciate it.
import React, { useState, useEffect } from "react";
import {
StyleSheet,
View,
Text,
TouchableOpacity,
SafeAreaView,
FlatList,
} from "react-native";
import {
Calendar,
Agenda,
Timeline,
ExpandableCalendar,
TimelineList,
CalendarProvider,
} from "react-native-calendars";
import Modal from "react-native-modal";
import FlightItem from "./FlightItem";
import UserStore from "../stores/UserStore";
import ReservationForm from "./ReservationForm";
import { db } from "../FirebaseConfig";
import {
collection,
addDoc,
query,
where,
getDocs,
onSnapshot,
deleteDoc,
doc,
} from "firebase/firestore";
import { formatISO } from "date-fns";
const CalendarComponent = () => {
const userDetails = UserStore;
const [selectedDate, setSelectedDate] = useState(
formatISO(new Date(), { representation: "date" })
);
const [isModalVisible, setIsModalVisible] = useState(false);
const [selectedFlight, setSelectedFlight] = useState(null);
const [editingReservation, setEditingReservation] = useState(null);
//const [items, setItems] = useState({});
const [items, setItems] = useState({ [selectedDate]: [] });
const [refresh, setRefresh] = useState(false); // Move this line here
//console.log(userDetails);
const userID = userDetails.userID;
useEffect(() => {
const currentDate = formatISO(new Date(), { representation: "date" });
if (currentDate) {
loadReservations(currentDate);
}
const reservationsRef = collection(db, "reservations");
const q = query(reservationsRef);
const unsubscribe = onSnapshot(q, (snapshot) => {
const reservations = {};
snapshot.forEach((doc) => {
const data = doc.data();
const date = data.date;
if (!reservations[date]) {
reservations[date] = [];
}
reservations[date].push({
id: doc.id,
start: data.startTime,
end: data.endTime,
title: `Aircraft: ${data.selectedAircraftValue}n${data.firstName} ${data.lastName}`,
color: aircraftColors[data.selectedAircraftValue] || "#000000",
});
});
console.log("Updated reservations:", reservations);
setItems(reservations);
});
return () => {
unsubscribe();
};
}, [refresh]);
const onDayPress = (day) => {
if (day.dateString) {
setSelectedDate(day.dateString);
loadReservations(day.dateString);
}
};
const onBookFlight = () => {
setEditingReservation(null);
setIsModalVisible(true);
};
const aircraftColors = {
N2875Z: "#FF0000",
N6351Q: "#00FF00",
N67890: "#0000FF",
// Add more aircraft and colors as needed
};
const onEditReservation = (reservation) => {
setEditingReservation(reservation);
setIsModalVisible(true);
};
const loadReservations = async (date) => {
const reservationsRef = collection(db, "reservations");
const q = query(reservationsRef, where("date", "==", date));
try {
const querySnapshot = await getDocs(q);
const newItems = { ...items };
newItems[date] = [];
await Promise.all(
querySnapshot.docs.map(async (doc) => {
const data = doc.data();
const { id } = doc;
newItems[date].push({
id,
start: data.startTime,
end: data.endTime,
title: `Aircraft ${data.selectedAircraftValue || "N/A"}n${
data.firstName
} ${data.lastName}`,
color: aircraftColors[data.selectedAircraftValue] || "#000000",
});
})
);
setItems(newItems);
} catch (error) {
console.error("Error fetching reservations: ", error);
}
};
const addOrUpdateReservation = async (date, reservation) => {
const reservationData = {
date,
userID: userDetails.userID,
firstName: userDetails.first,
lastName: userDetails.last,
club: userDetails.club,
...reservation,
selectedAircraftValue: reservation.selectedAircraftValue, // Add this line
};
try {
await addDoc(collection(db, "reservations"), reservationData);
setIsModalVisible(false);
setRefresh(!refresh); // Add this line to force a re-render
} catch (error) {
console.error("Error adding reservation: ", error);
}
};
const handleDelete = async (id) => {
// Delete the reservation from the database
try {
await deleteDoc(doc(db, "reservations", id));
setIsModalVisible(false);
setRefresh(!refresh);
} catch (error) {
console.error("Error deleting reservation: ", error);
}
};
const onModalClose = () => {
setSelectedFlight(null);
setIsModalVisible(false);
setEditingReservation(null);
};
return (
<SafeAreaView style={styles.container}>
{/* ...existing components... */}
<CalendarProvider
date={selectedDate}
onDateChanged={onDayPress}
showTodayButton
disabledOpacity={0.6}
>
<ExpandableCalendar firstDay={1} />
<TimelineList
events={items[selectedDate] || []}
timelineProps={{
format24h: true,
unavailableHours: [
{ start: 0, end: 6 },
{ start: 22, end: 24 },
],
overlapEventsSpacing: 8,
rightEdgeSpacing: 24,
}}
showNowIndicator
initialTime={{ hour: 9, minutes: 0 }}
onEventPress={(event) => {
console.log("Event pressed:", event);
}}
/>
</CalendarProvider>
{/* Add Reservation Button */}
<TouchableOpacity
style={styles.addReservationButton}
onPress={onBookFlight}
>
<Text style={styles.addReservationButtonText}>+</Text>
</TouchableOpacity>
{/* Rest of your components */}
<Modal isVisible={isModalVisible} onBackdropPress={onModalClose}>
<View style={styles.modalContainer}>
<Text style={styles.modalTitle}>
{editingReservation ? "Edit Reservation" : "New Reservation"}
</Text>
<ReservationForm
selectedAircraftValue={
editingReservation ? editingReservation.selectedAircraftValue : ""
}
onSave={(reservation) => {
addOrUpdateReservation(selectedDate, reservation);
}}
onCancel={() => setIsModalVisible(false)}
onDelete={() =>
handleDelete(editingReservation ? editingReservation.id : "")
}
editingReservation={editingReservation}
editing={Boolean(editingReservation)} // Add this line
/>
</View>
</Modal>
</SafeAreaView>
);
};
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: "#F5FCFF",
},
modalContainer: {
backgroundColor: "white",
borderRadius: 10,
padding: 20,
},
modalTitle: {
fontSize: 18,
fontWeight: "bold",
marginBottom: 10,
},
modalText: {
fontSize: 16,
marginBottom: 20,
},
modalButtons: {
flexDirection: "row",
justifyContent: "flex-end",
},
modalButton: {
padding: 10,
marginLeft: 10,
backgroundColor: "#2196F3",
borderRadius: 5,
},
modalButtonText: {
color: "white",
fontWeight: "bold",
},
emptyDataContainer: {
flex: 1,
alignItems: "center",
justifyContent: "center",
padding: 10,
},
emptyDataText: {
fontSize: 16,
color: "#777",
},
header: {
flexDirection: "row",
justifyContent: "space-between",
alignItems: "center",
paddingHorizontal: 20,
paddingVertical: 10,
backgroundColor: "#2196F3",
},
headerTitle: {
fontSize: 20,
color: "white",
fontWeight: "bold",
},
headerButton: {
paddingHorizontal: 10,
paddingVertical: 5,
borderRadius: 5,
backgroundColor: "white",
},
headerButtonText: {
fontSize: 16,
color: "#2196F3",
fontWeight: "bold",
},
addReservationButton: {
position: "absolute",
bottom: 20,
right: 20,
backgroundColor: "#2196F3",
borderRadius: 50,
width: 60,
height: 60,
justifyContent: "center",
alignItems: "center",
zIndex: 10,
},
addReservationButtonText: {
color: "white",
fontSize: 40,
},
});
export default CalendarComponent;
here is the logged data that comes through.
Updated reservations: {“2023-04-21”: [{“color”: “#FF0000”, “end”: “17:42”, “id”: “3DKiauB0flrGTLQhCIRc”, “start”: “16:42”, “title”: “Aircraft: N3498G
Bob Lastname”}]
How to show a message on hover on page load in javascript? [closed]
I have a php code
as shown below in which when Line
A is executed, I see a message javascript:alert('Not found')
at the bottom left (of the page) on hover. I am wondering if it is best from the user experience point of view.
if (condition) {
/*
code
*/
if (file_exists($path)) {
$choices[0][1] = 'display_file.php?path=' . addressencode($path);
} else {
$choices[0][1] = "javascript:alert('Not found')"; // Line A
}
continue;
}
if (1 == sizeof($choices)) {
$address = $choices[0][1];
}
<area shape="rect" href="<?php echo $address; ?>"
onclick="if(this.getAttribute('href') !== 'javascript:alert('Not found')' && parent.document.body.rows == '*,0' ) parent.document.body.rows = '55%,45%';"
alt="<?php echo implode(', ', $records); ?>" /> <!-- Line B -->
Problem Statement:
I am wondering what changes I need to make at Line
A and Line B
so that on hover I can show a different message (at the bottom left of the webpage) or any changes at Line A and Line B which can improve the user experience.
How can I make arcade and matter physics interact with each other?
I’m making a top down game and I have everything coded to run on arcade physics. The only thing I need the matter physics engine for is sloped tiles used for diagonal walls.
Here are screenshots of what I have.
I haven’t figured out a way to have the two collide properly. I tried using this.physics.add.collider(this.player.sprite, groundLayer); which does work, but the slopes are turned into rectangles.
With matter, it seems like the collision is enabled by default, and the only instance of using a collision code is to trigger an event, which isn’t necessary.
I don’t want to convert my player sprite to matter since it’s a lot of work and quite complicated with my level of knowledge.
Here’s my code.
My level file:
import Player from './Player.js';
export default class Field01 extends Phaser.Scene {
constructor () {
super({
key: 'field01',
physics: {
arcade: {
debug: true,
gravity: { y: 0 }
},
matter: {
debug: true,
gravity: { y: 0 },
debugShowBody: true,
debugBodyColor: 0x0000ff
}
}
});
}
preload()
{
this.load.image('tiles', 'assets/tilemaps/tiles/overworld-ground.png');
this.load.tilemapTiledJSON('map', 'assets/tilemaps/maps/Field01.json');
this.load.image('ground', 'assets/platform.png');
this.load.spritesheet('dude', 'assets/sprites/characters/link.png', { frameWidth: 16, frameHeight: 24 });
}
create()
{
var platforms;
var player;
this.map = this.make.tilemap({ key: 'map' });
this.map.landscape = this.map.addTilesetImage('fieldfare', 'tiles');
const groundLayer = this.map.createLayer("ground", [this.map.landscape], 0, 0);
this.map.setCollisionBetween(2,9);
this.cameras.main.setSize(256,224);
this.cameras.main.setBounds(0, 0, this.map.widthInPixels, this.map.heightInPixels);
this.player = new Player(this, 352, 48);
this.add.existing(Player);
this.cameras.main.startFollow(this.player.sprite);
this.cameras.main.setDeadzone(4,4);
platforms = this.physics.add.staticGroup();
platforms.create(64, 64, 'ground');
groundLayer.setCollisionByProperty({ collides: true });
this.matter.world.convertTilemapLayer(groundLayer);
this.physics.add.collider(this.player.sprite, groundLayer);
this.physics.add.collider(this.player.sprite, platforms, function(player, platforms) { this.scene.switch('Level1'), player.y += 48}, null, this);
}
update() {
this.player.update();
}
}
My player file:
export default class Player {
constructor(scene, x, y) {
this.scene = scene;
const anims = scene.anims;
anims.create({
key: 'turn1',
frames: [ { key: 'dude', frame: 32 } ],
frameRate: 20
});
anims.create({
key: 'rdown',
frames: anims.generateFrameNumbers('dude', { start: 0, end: 7 }),
frameRate: 16,
repeat: -1
});
anims.create({
key: 'rright',
frames: anims.generateFrameNumbers('dude', { frames: [ 8, 9, 10, 11, 12, 13, 14, 15 ] }),
frameRate: 16,
repeat: -1
});
anims.create({
key: 'rup',
frames: anims.generateFrameNumbers('dude', { frames: [ 16, 17, 18, 19, 20, 21, 21, 23 ] }),
frameRate: 16,
repeat: -1
});
anims.create({
key: 'rleft',
frames: anims.generateFrameNumbers('dude', { frames: [ 24, 25, 26, 27, 28, 29, 30, 31 ] }),
frameRate: 16,
repeat: -1
});
this.sprite = scene.physics.add.sprite(x, y, "dude", 0).setSize(16, 16).setOffset(0, 8);
this.sprite.anims.play("rdown");
this.gamepad = scene.input.gamepad.once('down', function (pad, button, index) {
this.gamepad = pad;
}, this);
}
update() {
const gamepad = this.gamepad;
const sprite = this.sprite;
const speed = 90;
const prevVelocity = sprite.body.velocity.clone();
sprite.body.setVelocity(0);
if (gamepad.right && gamepad.up) {
sprite.body.setVelocityX(speed);
sprite.body.setVelocityY(-speed);
} else if (gamepad.right && gamepad.down) {
sprite.body.setVelocityX(speed);
sprite.body.setVelocityY(speed);
} else if (gamepad.left && gamepad.up) {
sprite.body.setVelocityX(-speed);
sprite.body.setVelocityY(-speed);
} else if (gamepad.left && gamepad.down) {
sprite.body.setVelocityX(-speed);
sprite.body.setVelocityY(speed);
} else if (gamepad.left) {
sprite.body.setVelocityX(-speed);
} else if (gamepad.right) {
sprite.body.setVelocityX(speed);
} else if (gamepad.up) {
sprite.body.setVelocityY(-speed);
} else if (gamepad.down) {
sprite.body.setVelocityY(speed);
}
sprite.body.velocity.normalize().scale(speed);
if (gamepad.left) {
sprite.anims.play("rleft", true);
} else if (gamepad.left && gamepad.down) {
sprite.anims.play("rleft", true);
} else if (gamepad.left && gamepad.up) {
sprite.anims.play("rleft", true);
} else if (gamepad.right && gamepad.down) {
sprite.anims.play("rright", true);
} else if (gamepad.right && gamepad.up) {
sprite.anims.play("rright", true);
} else if (gamepad.up) {
sprite.anims.play("rup", true);
} else if (gamepad.right) {
sprite.anims.play("rright", true);
} else if (gamepad.down) {
sprite.anims.play("rdown", true);
} else {
sprite.stopOnFrame(sprite.anims.currentAnim.getFrameAt(0))
}
}
}
Here’s my game config file;
import Field01 from "./Field01.js";
var config = {
type: Phaser.AUTO,
width: 256,
height: 224,
pixelArt: true,
input: {
gamepad: true
},
physics: {
default: 'arcade',
arcade: {
gravity: { y: 0 },
debug: true
}
},
scene: [ Field01 ]
}
var game = new Phaser.Game(config);
And my index file:
<!DOCTYPE html>
<html>
<head>
<script src="phaser.js"></script>
<script src="matter.js"></script>
</head>
<body>
<script type="module" src="game.js"></script>
</body>
</html>
Anything I can do?
If I have to change to matter, then how would I properly convert it? This is just a last resort if nothing else is possible.
How to disable passport.js sessions based on request?
Passport allows sessions with the passport-local library with the following code, but I can’t figure a way to toggle session
based on the request object.
Current code: router.post('/login', passport.authenticate('local', { session: true }), login)
Request contains the persist
boolean in req.body
I figured that I can pass the request to my Strategy
function with the following code:
passport.use(
new Strategy(
{ usernameField: 'email', passReqToCallback: true },
passportStrategy
)
)
export const passportStrategy = async (
req: Request,
email: string,
password: string,
done: Function
) => {
try {
const user = await UserModel.findOne({ email })
if (!user) {
return done(null, false, { message: 'Incorrect username.' })
}
const matches = await comparePassword(password, user.password!)
if (!matches) {
return done(null, false, { message: 'Incorrect password.' })
}
return done(null, user)
} catch (err) {
return done(err)
}
}
but that doesn’t affect the session code.
The reason I want to disable sessions is in case users are on a public computer, so perhaps there’s a way of deleting the session either immediately client side or in my route handler?
Uncaught TypeError: e.preventDefult is not a function ( Also i am trying to updating my .js file to try solve the problem but not working)
I am trying to build a messaging app in php and javascript languages
But I have a problem, which is that when I linked the index file with the signup.js file
And when I opened the file in a local host, I was exposed to this problem: Uncaught TypeError: e.preventDefult is not a function
(I tried to modify the function in the java file, but the browser does not accept the modification, no matter how much I update the file, I do not know why and how I can solve the problem)
JAVASCRIPT CODE
const form = document.querySelector(".signup form"),
continueBtn = form.querySelector(".button input");
form.onsubmit = (e)=>{
e.preventDefault(); //formun gönderilmesini engelleme
}
continueBtn.onclick = () =>{
let xhr = new XMLHttpRequest(); //creating XML object
xhr.open("POST" , "php/signup.php", true);
xhr.onload = ()=>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
console.log(data);
}
}
}
xhr.send();
}
PHP CODE
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viweport" content="width=device-width, initial-scale=0.1">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>OnlineMesajlaşmaUygulaması</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="http://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.2/css/all.min.css"/>
</head>
<body>
<div class="wrapper">
<section class="form signup">
<header>Mesajlaşma Uygulaması</header>
<form action="#">
<div class="error-txt">This is an error message!</div>
<div class="name-details">
<div class="field input">
<label>First Name</label>
<input type="text" placeholder="First Name ">
</div>
<div class="field input">
<label>Last Name</label>
<input type="text" placeholder="Last Name ">
</div>
</div>
<div class="field input">
<label>Email Address</label>
<input type="email" placeholder="Enter your email ">
</div>
<div class="field input">
<label>Password</label>
<input type="password" placeholder="Enter new password ">
<i class="fas fa-eye"></i>
</div>
<div class="field image">
<label>Select Image</label>
<input type="file">
</div>
<div class="field button">
<input type="submit" value="Continue to Chat">
</div>
</form>
<div class="link">Alredy Signed up?<a href="#">Login now</a> </div>
</section>
</div>
<script src="javascript/pass-show-hide.js"></script>
<script src="javascript/signup.js"></script>
</body>
</html>