I have a web app where I let user connect their Instagram Account. On web it works fine, but on mobile the user is redirected to Instagram In app browser and then when the user lands on callback url in the In app browser his session is not active and he is shown logged out of my web app. How can I force the callback to system browser? I am using Laravel.
Category: javascript
Category Added in a WPeMatico Campaign
Filtering an HTMLDropDownListFor depending on the ID
I want to be able to filter this dropdownlistfor where it will only display the items in a collection where the MemoId is 0
so far what I’ve done is this:
@Html.DropDownListFor(model => model.MemoTeplateId, new SelectList(ViewBag.lstSacntion.Where(Model => Model.MemoId == 0),"Id", "Name"), "-- Select Disciplinary --", new { @class = "form-control col-md-12" }
it shows me an error that says CS1977, but clicking the error link doesn’t show me any information besides the tooltip saying “Cannot use lambda expression as an argument to a dynamically dispatched operation.
Best Approach for Loading Next Question in Laravel Quiz App
I am Building a quiz app in laravel. I want to know which approach is the best for loading questions , either loading every question via API call or Loading all questions at a time & manipulate in JS?. The quiz will contain some 200 Questions for single quiz and the app has some 100 of users
For sample, i am loading questions all at once and manipulating via JS
Chrome browser page reloads when executing a Save or Save As using The File System Access API
I created a test html/js program (using VS-Code and Go Live) that simply increments some state variables that I could Save, Save As, and Open/Load to experiment with The File System Access API. When I Save, or Save As, the Chrome browser page reloads and resets the state variables back to their initial values of zero (not the values at the save event time). This problem does not occur when I Open/Load and read the state data from a local file – not sure why? The current state data is actually saved even though the page is reloaded and the state data is reset to initial values as shown below
let state = {
arr: [0],
dataA: 0,
dataB: 0,
dataC: 0,
fileHandle: null
}
When I simply made a copy of the test project folder and ran the program from the new copied folder, everything worked (Save, SaveAs, Open Load) without reloading the browser page – still not sure why? I then add this fs code to project and page reload problem occurred again whenever I tried to save or Save As. Again, data was saved, but Chrome browser reloaded, and state values were reset to initial values.
async function saveStateAS(options, data) {
const fileHandle = await showSaveFilePicker(options);
data.setState('updateFileHandle', fileHandle);
const writable = await fileHandle.createWritable();
const values = JSON.stringify(data.state);
await writable.write(values);
await writable.close();
console.log('Handle: ', date.state.fileHandle);
}
async function saveAndEdit(options, data) {
let fileHandle = data.state.fileHandle;
if (fileHandle === null) {
[fileHandle] = await window.showOpenFilePicker(options);
}
data.setState('updateFileHandle', fileHandle);
const values = JSON.stringify(data.state);
const writable = await fileHandle.createWritable();
await writable.write(values);
await writable.close();
}
Post request throws 405(METHOD NOT ALLOWED) while trying to post to an api
i am trying to create a simple front end that can interact with my api. Currently the api is okay I can GET data and POST my data when using POSTMAN client for the requests. So far I can get data from the server and load it into the frontend, but trying to post into the api is where I get the challenge.
this is the error that I get when i try to post the data
script.js:45
POST http://127.0.0.1:5500/users net::ERR_ABORTED 405 (Method Not Allowed)
(anonymous) @ script.js:45
to show you what i have done, here is the form I am trying to submit
<form>
First name: <input type="text" name="firstname" id="firstname"><br>
Last name: <input type="text" name="lastname" id="lastname"><br>
Age: <input type="number" name="age" id="age"><br>
<button type="submit">Send to backend</button>
</form>
Below is the javascript code contained in the frontend
// function updatePost(){
const firstname = document.getElementById('firstname')
const lastname = document.getElementById('lastname')
const age = document.getElementById('age')
const button = document.querySelector('button')
button.addEventListener('click',(e)=>{
e.preventDefault()
var obj = {
firstname:firstname.value,
lastname:lastname.value,
age:age.value
};
fetch('/users',{
method:"POST",
// headers:{
// "content-type":"application/json"
// },
body:JSON.stringify(obj)
})
})
// }
// updatePost()
And below is my post route which is the server side logic
app.post('/users', async(req,res)=>{
var {firstname,lastname,age} = req.body
console.log(req.body)
let conn;
try {
console.log(firstname,lastname,age)
conn = await pool.getConnection()
const result = await conn.query("insert into info (firstname, lastname,age) VALUES (?, ?, ?)",[firstname,lastname,age])
res.json({
"res":"your code is working denis"
})
} catch (error) {
res.send(error)
}finally {
// await poolModule.releaseConn(conn);
conn.release()
}
}
)
app.listen('3008',()=>{
console.log('server is working')
})
I feel that there is something I am missing, and would appreciate the help. incase more information is needed I can place all my codes here for the error to be reproduced. Thanks.
Migrating Nuxt v2 SSR to React with SSR
I’m trying to incrementally migrate a Nuxt v2 application to use React components, while still supporting SSR.
I have this component to wrap React within the Vue application.
The problem I face is that all Vue lifecycle hooks with access to the component seem to happen client side.
beforeMount is client-side, but beforeCreate can’t access the ref to mount the react HTML.
Is there any way to do this?
<template>
<div ref="container" class="react-wrapper" />
</template>
<script lang="ts">
import { createElement } from 'react';
import { renderToString } from 'react-dom/server';
import { createRoot } from 'react-dom/client';
import type { Root, Container } from 'react-dom/client';
import Vue, { PropType } from 'vue';
export default Vue.extend({
name: 'ReactWrapper',
inheritAttrs: false,
props: {
component: {
type: Function as PropType<string>,
required: true,
},
},
beforeMount(): void {
const container = this.$refs.container as Container;
if (container) {
this.reactRoot = createRoot(container);
this.updateReactComponent();
}
},
data(): { reactRoot: Root | null } {
return {
reactRoot: null,
};
},
methods: {
updateReactComponent(): void {
if (process.client) {
this.reactRoot?.render(
createElement(this.component, {
...this.$attrs,
})
);
} else {
const container = this.$refs.container as HTMLDivElement;
if (container) {
const html = this.renderReactComponent();
container.innerHTML = html;
}
}
},
renderReactComponent(): string {
try {
const html = renderToString(
createElement(this.component, {
...this.$attrs
})
);
return html;
} catch (error) {
console.error(
'[react-wrapper] Error rendering React component:',
error
);
return '';
}
},
},
computed: {
isClientRendered(): boolean {
return process.client;
},
},
watch: {
$attrs: {
deep: true,
handler(): void {
this.updateReactComponent();
},
},
},
});
</script>
How to track Xpath of an element when it changes due to change in browser zoom level
I have a button on the UI, and I am using the Xpath of the button to show some help (on the popover). Is there a way to know the xpath of a button if the placement changes due to a change in browser zoom level or resizing?
Date Parsing Issue with Discord Invite API Response in Google Apps Script
I am trying to make a function that will validate a Discord invite and check if the invite is temporary just from a Discord invite URL. If the invite is temporary, I want it to return the expiration date as a new Date. If it doesn’t expire, I want the function to return false.
async function getInviteExpiration(inviteUrl) {
// Extract the invite code from the URL
const regex = /discord.gg/([a-zA-Z0-9]+)/;
const match = inviteUrl.match(regex);
if (!match) {
throw new Error('Invalid invite URL');
}
const inviteCode = match[1];
const response = UrlFetchApp.fetch(`https://discord.com/api/invites/${inviteCode}?with_counts=true`);
if (response.getResponseCode() !== 200) {
throw new Error('Failed to fetch discord invite information');
}
const inviteData = JSON.parse(response.getContentText());
console.log(inviteData.expires_at); // Temporary, just for testing
console.log(new Date(inviteData.expires_at)); // Temporary, just for testing
if (inviteData.expires_at === null) {
return false; // Invite never expires
} else {
return new Date(inviteData.expires_at); // Return expiration date
}
}
I made a test function to test getInviteExpiration.
function test() {
const permanentUrl = "https://discord.gg/minecraft";
console.log(getInviteExpiration(permanentUrl)); // Expecting false
const tempUrl = "https://discord.gg/DdMJXskh";
console.log(getInviteExpiration(tempUrl)); // Expecting Date
}
And here is the outputted console,
null
Wed Dec 31 1969 18:00:00 GMT-0600 (Central Standard Time)
{}
2024-04-18T02:27:18+00:00
Wed Apr 17 2024 21:27:18 GMT-0500 (Central Daylight Time)
{}
Why is it that I’m getting empty objects when in the getInviteExpiration function, it was able to parse console.log(new Date(inviteData.expires_at))?
Angular download file from blob is twice the size as the original file
I have an api that returns a file as a ‘application/octet-stream’ which I then create into a blob and fake click in the browser so the user can download it. This works in all the cases I’ve tested where the files have an extension, but I have one file that doesn’t have an extenstion. I’m not even sure what type of file it is. But when it goes through this process, it is twice as large as the amount of data I pulled from the original API.
We have a swagger doc with the API that creates a download button and when I download the file from there it is the correct size.
This is what my blob creation and download looks like.
downloadFile(newFile: any, fileName:string) {
let file = new Blob([newFile], {type: 'application/octet-stream'});
let element = document.createElement('a');
let url = URL.createObjectURL(file);
element.setAttribute('href', url);
element.setAttribute('download', fileName);
element.style.display = 'none';
document.body.appendChild(element);
element.click(); // simulate click
document.body.removeChild(element);
}
I also tried adding this to the beginning of my function, but shrank the file down to about a 10th of it’s original size.
let array = new Uint8Array(newFile.length);
for (var i = 0; i < newFile.length; i++){
array[i] = newFile.charCodeAt(i);
}
Any idea how I can make this work or make a downloader that works for all files?
How to submit an image dynamically along with an existing form? Or even replace the content of a file element?
In this thread, Is this good way how to resize image before upload?,
DevelJoe shows a good way to get a resized image data. But how to upload the data along with an existing form (having other input elements) to the server as another file element? Or even replace the original file with the resized image?
Why states will never change in the push listener while setState did change it




I received 4 times pushes.
The state “time” did change as it shows on the html.
But it didn’t change when I print it on the push listener?
Why? Is there any way to fix it?
The push carries an id. I need to compare current recorded id with the push id to decide if it needs to do something
Thank you for reading this question! I appreciate it if you could enlighten me!
Why does my .Refine is not working properly when I tried to make a conditional input field?
I created a conditional input field wherein if the user selected yes, it will prompt another 3 input fields. How can I make the input field required and show a warning if the if the user selected yes?
const FormSchema = z.object({
type: z.enum(["yes", "no"], {
required_error: "You need to select a notification type.",
}),
dryRunDate: z.string().optional(),
dryRunStart: z.string().optional(),
dryRunEnd: z.string().optional(),
}).refine(data => {
if (data.type === 'yes') {
return data.dryRunDate && data.dryRunStart && data.dryRunEnd;
}
return true;
});
export default function RadioGroupForm() {
const form = useForm<z.infer<typeof FormSchema>>({
resolver: zodResolver(FormSchema),
defaultValues: {
type: "no",
dryRunDate: "",
dryRunStart: "",
dryRunEnd: ""
}
});
const hasDryRun = form.watch(“type”);
This is my form.tsx
<Form {...form}>
<form onSubmit={form.handleSubmit(onSubmit)} className="w-2/3 space-y-6">
<FormField
control={form.control}
name="type"
render={({ field }) => (
<FormItem className="space-y-3">
<FormLabel>Optional;</FormLabel>
<FormControl>
<RadioGroup
onValueChange={field.onChange}
defaultValue={field.value}
className="flex flex-col space-y-1"
>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="yes" />
</FormControl>
<FormLabel className="font-normal">yes</FormLabel>
</FormItem>
<FormItem className="flex items-center space-x-3 space-y-0">
<FormControl>
<RadioGroupItem value="no" />
</FormControl>
<FormLabel className="font-normal">no</FormLabel>
</FormItem>
{hasDryRun === "yes" && (
<>
<FormField
control={form.control}
name="dryRunDate"
render={({ field }) => (
<FormItem>
<FormLabel>dryRunDate</FormLabel>
<FormControl>
<Input type="date" placeholder="date" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dryRunStart"
render={({ field }) => (
<FormItem>
<FormLabel>Dry Run Start</FormLabel>
<FormControl>
<Input type="time" placeholder="start" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<FormField
control={form.control}
name="dryRunEnd"
render={({ field }) => (
<FormItem>
<FormLabel>Dry Run End</FormLabel>
<FormControl>
<Input type="time" placeholder="end" {...field} />
</FormControl>
<FormMessage />
</FormItem>
)}
/>
</>
)}
</RadioGroup>
</FormControl>
<FormMessage />
</FormItem>
)}
/>
<Button type="submit">Submit</Button>
</form>
</Form>
How to get AudioBuffer data from an HTML video element (MediaElementAudioSourceNode)
I have a MediaElementAudioSourceNode obtained via:
audioCtx.createMediaElementSource(videoElement)
How do I get a buffer of audio data from this that is suitable for input to music-tempo?
Pass … MusicTempo [a] buffer … in the following format: non-interleaved IEEE754 32-bit linear PCM with a nominal range between -1 and +1[. T]hat is, a [32-bit] floating point buffer, with each [sample] between -1.0 and 1.0. This format is used in the AudioBuffer interface of Web Audio API.
I tried the following code, but timeDomainDataArray is filled with all 0 values:
let audioCtx = new AudioContext();
let source = audioCtx.createMediaElementSource(videoElement);
const analyser = audioCtx.createAnalyser();
const timeDomainDataArray = new Float32Array(analyser.fftSize);
analyser.getFloatTimeDomainData(timeDomainDataArray);
source.connect(analyser);
source.connect(audioCtx.destination);
console.log({ source });
console.table(timeDomainDataArray);
(The code above was run inside a button click-handler, after manually starting video playback.)
I believe this is similar to code from another project, but I’m not sure what the difference is with my code.
The ultimate goal is to detect the beats in a YouTube video so they can be visualized.
How is handle huge users to register in a web application
Suppose a thousand people visit the register page in the web application every day and send their information to the servlet for the register.
What is the best way to get data in js file (register.jsp)?
An idea that came to my mind is to consider an array and put the data entered by the user in it, for example, all the names in index zero of the array, all the lastnames in index 2 and so on.
Is this idea correct? Do we need to do this in the view or should this only be handled in the controller?
I have written a sample code to send the data to the view as a simple array, but I think the better idea is the one I mentioned above.
The code is:
<script type="text/javascript">
$(document).ready(function() {
$("#register").click(function() {
var json_data = [{
"name": $('#firstname').val(),
"lastname":$('#lastname').val(),
"email":$('#email').val(),
"password1":$('#password').val(),
"Address":
{
"state":$('#state').val(),
"country":$('#country').val(),
"city":$('#city').val()
}
}];
let data = [];
data.push(json_data);
$.ajax({
url: 'RegisterController',
type: 'POST',
data: data,
dataType: 'json',
contentType: 'application/json',
mimeType: 'application/json',
});
});
});
If my idea is correct, I would be grateful if you could help me in writing the code.
Slide client logo from right to left infinite loop
I am using the code below for my client’s logo. This code creates an infinite slider that slides from right to left.
I am also using jQuery to append duplicate slides for the infinite loop.
However, I’m encountering an issue: the code resets automatically after the slide reaches the fourth card.
would you help me out what is the issue here?
$(document).ready(function() {
// Clone cards to create infinite loop
$(".marqueme").clone().appendTo(".marquestarthere");
});
.testimonial-cards {
list-style: none;
display: flex;
gap: 56px 31px;
margin: 0 auto;
width: max-content;
flex-wrap: nowrap;
}
.testimonial-cards li {
width: 100%;
max-width: 500px;
min-height: 200px;
}
.marqueslide .marqueme {
flex: 0 0 auto;
margin-right: 20px;
border:1px solid #000
}
/* solution */
.marquestarthere {
animation: marquee 8s linear infinite; /* Set the animation here */
}
.marquestarthere:hover{
animation-play-state: paused;
}
@keyframes marquee {
0%,100% {
transform: translateX(0);
}
99.999% {
transform: translateX(-50%);
}
}
<div class="marqueslide">
<ul class="testimonial-cards marquestarthere">
<li class="marqueme">Card 1</li>
<li class="marqueme">Card 2</li>
<li class="marqueme">Card 3</li>
<li class="marqueme">Card 4</li>
<li class="marqueme">Card 5</li>
<li class="marqueme">Card 6</li>
<li class="marqueme">Card 7</li>
<li class="marqueme">Card 8</li>
<li class="marqueme">Card 9</li>
<li class="marqueme">Card 10</li>
<!-- duplicate cards append here-->
</ul>
</div>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>