Why does FormData cause 400 bad request?

I have the following situation. This works perfectly, but when I try to use formData to enable file upload I get a 400 (bad request) error. I have tried all manner of content-type and enctype, but nothing seems to work. Any ideas as to what’s going wrong?

You can see the commented lines. if I switch to those I always get a 400 ‘bad request’

Visual Studio 2022, Net 8.

My Form (BS5 Modal)

<form id="frmItemLocalForm" method="post" name="frmItemLocalForm" novalidate="novalidate" enctype="multipart/form-data">
    @Html.AntiForgeryToken()
    <input type="hidden" name="controlId" id="controlId" value="@ViewData["controlid"]" />
    <input type="hidden" name="itemId" id="itemId" value="@ViewData["itemId"]" />
    <input type="hidden" asp-for="UserDocument.Created" name="Created" />

    <!--Modal Header-->
    <div class="modal-header">
        <h4 class="modal-title">Edit User Document</h4>
        <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
    </div>

    <!-- Modal body -->
    <div class="modal-body">

        <div class="row my-1">
            <label class="col-form-label col-md-2">Name</label>
            <div class="col-md-10">
                <input type="text" class="form-control" placeholder="Name" asp-for="UserDocument.DocumentName" name="DocumentName" data-rule-required="true" />
            </div>
        </div>

        <div class="row my-1">
            <label class="col-form-label col-md-2">File</label>
            <div class="col-md-10">
                <input type="file" class="form-control fileUpload" placeholder="User Document" name="userdocumentfileupload" id="userdocumentfileupload" data-rule-required="true" required />
                <br />@Model.UserDocument?.DocumentName @Model.UserDocument?.FileName
            </div>
        </div>
    </div>

    <!-- Modal footer -->
    <div class="modal-footer">
        <button type="submit" id="editLocalForm" class="btn btn-primary">OK</button>
        <button type="button" class="btn btn-danger close-button" data-bs-dismiss="modal">Close</button>
    </div>
</form>
$(document).on("click", "#editLocalForm", function (e) {
    e.preventDefault();
    e.stopPropagation();

    var myform = $("#frmItemLocalForm");
    var valid = myform.valid();

    if (valid) {

        var formData = new FormData();

        //$(".fileUpload").each(function () {
        //    var fileInput = $(this)[0];
        //    var file = fileInput.files[0];

        //    if (file.size > 0) {
        //        formData.append($(this).attr("id"), file);
        //    }
        //});

        //formData.append("myFormData", myform.serialize());

        $.ajax({
            url: formUrl,
            data: myform.serialize(),//formData,
            dataType: "html",
            contentType: "application/x-www-form-urlencoded",
            processData: false,
            method: "post",
            success: function (result) {
                $(".close-button").click();
                table.ajax.reload(null, false);
            },
            error: function (err) {
                console.log(err);
            }
        });
    }
});

Stripe form submission creates payment token but doesn’t redirect despite successful token creation

I’m currently working on integrating Stripe payments into my web application. I’ve set up the form submission to create a payment token upon clicking the Stripe payment button. However, after successful token creation, the form doesn’t redirect as expected.

I’ve tried retrieving the complete form values upon clicking the payment button using JavaScript, and the payment token is indeed created. However, the redirection doesn’t occur. I’m uncertain whether the issue lies in my form submission or in Stripe’s configuration.

Here’s a snippet of my code:

          <form action="become-a-partner.php?action=stripe_payment" method="post"  enctype="multipart/form-data">
                             
                                    <div class="form-body">
                                       
                                        <hr>
                                        <div class="row p-t-20">
                                            <div class="col-md-6">
                                                <div class="form-group">
                                                    <label class="control-label">Restaurant Name</label>
                                                    <input type="text" name="res_name" class="form-control">
                                                   </div>
                                            </div>
// This is Stripe code where the payment dialog box opens for payment
// After payment done it dose not redirect 
<script
                src="https://checkout.stripe.com/checkout.js" class="stripe-button"
                data-key="<?php echo $publishableKey?>"
                data-amount="<?php echo 10000 ?>"
                data-name="<?php echo $_SESSION['user_name']; ?> "
                data-description="Membership Payment"
                data-image="images/img/logo_web.jpg"
                data-currency="usd"
                data-email="<?php echo $_SESSION['user_email']; ?>"
            >
            </script>
        
        
    </form>
                                  ```

Thank You and looking forward for solution

Is there a way to make a onclick event in Google Slides using Apps Scripts for a scoreboard?

So am trying to make a scoreboard thing for fun and I used this script which can make this function possible and this is where I get stuck the values are not updating when clicked on during presentatioin mode. What can I do to fix this problem?

I tried using this script:

function onOpen() {
  var presentation = SlidesApp.getActivePresentation();
  var slides = presentation.getSlides();

  slides.forEach(function(slide) {
    var shapes = slide.getShapes();

    shapes.forEach(function(shape) {
      if (shape.getText().asString().match(/^d+$/)) {
        var action = SlidesApp.newAction()
          .setFunction('increaseNumber')
          .setParameters({ shapeId: shape.getObjectId() })
          .build();

        shape.onShapeClicked().setAction(action);
      }
    });
  });
}

function increaseNumber(e) {
  var presentation = SlidesApp.getActivePresentation();
  var slide = presentation.getSlides()[0]; // Change the index as needed

  var shapeId = e.source.getObjectId();
  var shape = slide.getShapeById(shapeId);
  var text = shape.getText().asString();
  var number = parseInt(text);

  if (!isNaN(number)) {
    number += 1;
    shape.getText().setText(String(number));
  }
}

Tags

When I applied this and nothing happened when I clicked on the textbox so what did I do wrong?

How to return a custom headers with Retry-After in SvelteKit api/something/+server.js?

I’m using SvelteKit api/getinfo/+server.js and trying to return a Retry-After header.

export async function POST(requestEvent){
    // some code that is irrelevant  to my question.
    return new Response({status : 429, Retry-After : 60})
}

I get error with Parse failure. Can’t find After
I looked the header name here and it is the right name so maybe my syntax is wrong. How do I return the status : 429 and Retry-After : 60 (60 is for 60 seconds)

Script to copy a form field value of the same name from one PDF form to another in Acrobat

I have created a script (below) in Acrobat to copy a form field value from one PDF form to another but for whatever reason the script fails to perform as intended, i.e., copy the value to the other PDF form field. I should also add that I have tried running the script using a button with a mouse-up event and a menu item I have added to the PDF form as well. However, to my dismay, the script ends up copying the value to the JS console while the target PDF form field value remains empty. Any help regarding this subject matter is much appreciated.

// sample script to copy form field data from one PDF to another with the same form field name
var sourceFld = getField("dataSrc");
sourceFld.value = getField("dataSrc").value;// assign data/value to a var
var oTargetDoc = null;// script to access target doc
for(var i=0;i<app.activeDocs.length;i++){
  if(app.activeDocs[i] != this){
    oTargetDoc = app.activeDocs[i];
    break;
  }
}
if(oTargetDoc){
//get form field from target doc
  var targetFld = this.getField("dataSrc");
  targetFld.value = sourceFld.value;//copy data from source PDF field to target PDF data field
  
}
if(targetFld.value != ""){
  app.alert({
    cMsg: "Data Transfer Success!",
    Title: "EasyPDF™ Password Manager Copy Data",
    nIcon: 3
  });
  console.println(targetFld.value);//print the data copied to the target PDF form field to the JS console
}
else
  app.alert({
    cMsg: "Data Transfer Failed!",
    Title: "EasyPDF™ Password Manager Copy Data",
    nIcon: 3
  });

Ran script using a button as well as a menu item added to the form and script failed to perform as intended, i.e., copy a form field value from one PDF form to another.

How do I correctly resume a session for a user?

I’ve just started learning next.js (TypeScript) and I’ve run into a problem.

I need to authorize a user to restore his session. The authorization key is a token that is stored in cookies. How to implement this task correctly?

At the moment, I have simply created a component in which I have embedded RootLayout, and in the component itself I am already executing an API request to search for a user by token, but with this approach I get various errors. Perhaps there are some other options?

'use client';
import { fetcher } from '@/helpers/fetcher';
import { useUserStore } from '@/store/user';
import { QueryCache, useQuery } from '@tanstack/react-query';
import { deleteCookie, getCookie } from 'cookies-next';
import { useEffect } from 'react';

export default function Auth() {
    const { user, setUser } = useUserStore();
    const rememberToken = getCookie('remember_token');
    if (user == null && rememberToken != null) {        
        const { isSuccess, data, } = useQuery({
            queryKey: ['loginToken'],
            queryFn: async () => await fetcher(process.env.API + '/auth/login', {
                method: 'POST',
                headers: {
                    Accept: 'application/json',
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    remember_token: rememberToken,
                })
            }),
        })
        if (isSuccess && data != null) {
            const userData = data.user;
            setUser({
                id: userData.id,
                rememberToken: userData.remember_token,
                email: userData.email,
            }, true);
        } else deleteCookie('remember_token');
    }
    return <></>
}

P.s: The useUserStore was created using zustand to store global user information.

Variable scope and addEventlistener

I would be grateful if someone can explain this: Why in the below code the console.log(array) within the addEventlistener can retrieve the array content (while not the console.lo(array) outside the addEventlistener)

const input = document.getElementById('search')
let array = []
fetch('https://jsonplaceholder.typicode.com/users')
.then(resp=>resp.json())
.then(data=>{
    array = data.map(user => {
    return { name: user.name, email: user.email}
    });
})

console.log(array)

input.addEventListener('input',(e)=>{
    console.log(array)
})

So why the addEventListener is capable of retrieving data within the array and not the console.log above? thank you.

How to get context.params in V2 firebase functions

🙂

I am trying to migrate my firebas3 functions to V2.In firebase V1 I did:

exports.onOpenCourse = functions.firestore.
  document("courses/{courseId}") 
  .onUpdate(
    (change, context) => { 
      ...
      const id = context.params.courseId
      ...

So I was able to use the info in “context”.As I understand, in V2 I now should do something like:

const { onDocumentCreated, document } = require("firebase-functions/v2/firestore");
onDocumentCreated( 
  { document: ""courses/{courseId}",},   
  (event) => {
    const snapshot = event.data;
    const info = snapshot.data();

How do I get context.params info in firebase functions V2?

The relevant example in the docs seems to still use V1: https://firebase.google.com/docs/firestore/extend-with-functions

I guess the core issue is that I am confused about exactly what these new functions are returning.
For example: According to the docs I found https.onCall returns any. Can I count on any to always contain params and data? https://firebase.google.com/docs/reference/functions/firebase-functions.https.md#httpsoncall

Any help would be appreciated!

j ai mis mon bot sur un vps debian est j ai toujour le meme probleme meme avec un vpn “‘UND_ERR_CONNECT_TIMEOUT'” [closed]

root@srv459673:~/ODAProtect# node main
La commande EmbedCreate.js a été chargée!
La commande ban.js a été chargée!
La commande banlist.js a été chargée!
La commande clear.js a été chargée!
La commande giveaway.js a été chargée!
La commande help.js a été chargée!
La commande info.js a été chargée!
La commande kick.js a été chargée!
La commande leaderboard.js a été chargée!
La commande lock.js a été chargée!
La commande mute.js a été chargée!
La commande ping.js a été chargée!
La commande progress.js a été chargée!
La commande rank.js a été chargée!
La commande setantiraid.js a été chargée!
La commande setlogs.js a été chargée!
La commande setstatus.js a été chargée!
La commande slowmode.js a été chargée!
La commande ticketrecrute.js a été chargée!
La commande ticketsupport.js a été chargée!
La commande unban.js a été chargée!
La commande unlock.js a été chargée!
La commande unmute.js a été chargée!
La commande warn.js a été chargée!
La commande warnlist.js a été chargée!
Evenement guildCreate.js chargé avec succès !
Evenement guildMemberAdd.js chargé avec succès !
Evenement interactionCreate.js chargé avec succès !
Evenement messageCreate.js chargé avec succès !
Evenement ready.js chargé avec succès !
node:internal/process/promises:288
            triggerUncaughtException(err, true /* fromPromise */);
            ^

ConnectTimeoutError: Connect Timeout Error
    at onConnectTimeout (/root/ODAProtect/node_modules/@discordjs/rest/node_modules/undici/lib/core/connect.js:186:24)
    at /root/ODAProtect/node_modules/@discordjs/rest/node_modules/undici/lib/core/connect.js:133:46
    at Immediate._onImmediate (/root/ODAProtect/node_modules/@discordjs/rest/node_modules/undici/lib/core/connect.js:174:9)
    at process.processImmediate (node:internal/timers:476:21) {
  code: 'UND_ERR_CONNECT_TIMEOUT'
}

meme avec filezila j ai se probleme et avec un vpn c’est pareil je suis sur hostinger

je me suis mis sur un vpn ca fonctionne pas j’ai reinstaler os debian 11 toujours rien c’est le support du vps qui m’envois

how to stop onclick action on javascript?

When the button is clicked, I want the spiners to appear for 3 seconds and then disappear. i can make

visible but cant make invisible again

function stoploading() {
  document.getElementById('loading').style.visibility = 'visible';
}
<button class="btn btn-danger d-inline-flex align-items-center" type="button">ATTACK</button>

<div class="col text-white m-5 px-5">
  <div id="loading" class="spinner-border text-primary load_icon" role="status">
    <span class="visually-hidden">Loading...</span>
  </div>
</div>

Best VSCode extensions or tools for automatic path updates in imports and renaming tags when moving or renaming Vue components?”

I planning to start moving my frontend code into better organized structure. I will be moving files to diffrent folders, renaming files to be more precise. But i dont know any good tools for this
What are the tools that automatically can be helpfull?

For example, like Vetur extension.

If i move a vue file/component to another folder, it will automatically update the path in another folder in all import statemtns. Thats good but when I rename a component, it wont automaticlly rename the old tags. I need tools for tasks like this

Are thre any good tools for this or VSCode extensions?

I know that:
https://code.visualstudio.com/updates/v1_24#_update-import-paths-when-a-file-is-moved-or-renamed
exists but i use JS not TS. Also, it doesnt rename the tags.

Unable to get GM_notification function to work in Tampermonkey userscript (chrome, OSX)

I’m trying to re-write some of my Tampermonkey scripts to use some of the built in TM/GM functions, but I can’t get them to work. An example is the GM_Notification function.

I’m testing it out using the example GM_notification from the documentation. Here is the complete userscript file contents:

// ==UserScript==
// @name   Test Notification
// @namespace http://tampermonkey.net/
// @version   2024-01-06
// @description  try to take over the world!
// @author    You
// @match  https://gist.github.com/EtienneDG/fe32d3213d87f79e0da0f829e73ee4ab
// @icon   https://www.google.com/s2/favicons?sz=64&domain=github.com
// @grant  GM_notification
// @grant  GM.notification
// @grant unsafeWindow
// @sandbox JavaScript
// ==/UserScript==

(function() {
  'use strict'

  console.log('Loaded test notification')

  console.log('About to execute GM_notification...');

  GM_notification({
    text: "This is the notification message.",
    title: "Notification Title",
    url: 'https:/google.com/',
    onclick: (event) => {
      // The userscript is still running, so don't open example.com
      event.preventDefault();
      // Display an alert message instead
      alert('I was clicked!')
    },
  });

  console.log('Executed GM_notification')
})()

And when I go to the page that loads this script, I get absolutely no notification/alert, or even an error.
The console output is below:

content: normal start event processing for lr2kbof7.baa (1 to run)
VM3242 content.js:55 env: schedule "Test Notification" for document-idle
VM3242 content.js:53 env: inject "Test Notification" now
VM3242 content.js:73 content: DOMContentLoaded
VM3242 content.js:54 env: run "Test Notification" now  (0 requires)
userscript.html?name=Test-Notification.user.js&id=a8f4d506-9af0-45b8-8eed-362488ac963e:21 Loaded test notification
userscript.html?name=Test-Notification.user.js&id=a8f4d506-9af0-45b8-8eed-362488ac963e:23 About to execute GM_notification...
userscript.html?name=Test-Notification.user.js&id=a8f4d506-9af0-45b8-8eed-362488ac963e:37 Executed GM_notification
VM3242 content.js:73 content: load

So the script clearly runs, but I don’t see any notification or any error in the console logs.

I have tried using the async GM.notification as well:

// ==UserScript==
// @name   Test Notification
// @namespace http://tampermonkey.net/
// @version   2024-01-06
// @description  try to take over the world!
// @author    You
// @match  https://gist.github.com/EtienneDG/fe32d3213d87f79e0da0f829e73ee4ab
// @icon   https://www.google.com/s2/favicons?sz=64&domain=github.com
// @grant  GM_notification
// @grant  GM.notification
// @grant unsafeWindow
// @sandbox JavaScript
// ==/UserScript==

(async function() {
  'use strict'

  console.log('Loaded test notification')

  console.log('About to execute await GM.notification...');

  const clicked = await GM.notification({ text: "Click me." });
  console.log('clicked:',clicked)

  console.log('Executed await GM.notification')
})()

But it was the same thing (no notification or errors)

I have tried a few things while debugging:

  1. Trying with the other @sandbox values: MAIN_WORLD, ISOLATED_WORLD, USERSCRIPT_WORLD, raw, DOM
  2. Does’t seem to be any permissions issues with the TM plugin or script
  3. The Add GM functions to this or window is set to On in the script settings
  4. Set Run At to: document-start, document-body, document-end
  5. For the Position setting, I tried 1, 3 and 7
  6. Consulted the Google Gods, and found some similar threads (Example: Uncaught ReferenceError: GM_notification is not defined), but ultimately I haven’t found anything that fixes it.

Local Specs:

  • OS: macOS Big Sur
  • Browser: Chrome Version 120.0.6099.129 (Official Build) (x86_64)
  • Tampermonkey Version: v5.0.0

Any help would be appreciated. Thank you.

Tanstack React Query not importing

I am trying to implement tanstack react query into a project I am working on to manage state.

I am trying to set it up alongside a (tutorial for using react query with nextjs 13, and while I feel I am following it completely, I am getting all sorts of import errors.

The error I am getting is this:

./node_modules/@tanstack/react-query/build/modern/HydrationBoundary.js
Attempted import error: 'hydrate' is not exported from '@tanstack/query-core' (imported as 'hydrate').

Import trace for requested module:
./node_modules/@tanstack/react-query/build/modern/HydrationBoundary.js
./node_modules/@tanstack/react-query/build/modern/index.js
./src/app/_components/providers/TanstackProvider.tsx

but in my console I am getting the same issue with useQueries, useMutation, useMutations, useSuspenseBoundary and many others, quite possibly everything.

I have @tanstack/react-query version 5.17.7 installed but I have also tried downgrading to 4.35.3 and received the same error.

I got as far as creating a tanstack provider and attempting to do my first query before I realized nothing was being imported.

Here is my tanstack provider:

TanstackProver.tsx

"use client";

import { QueryClientProvider, QueryClient } from "@tanstack/react-query";
import { useState } from "react";

const TanstackProvider = ({ children }: { children: React.ReactNode }) => {
  const [queryClient] = useState(() => new QueryClient());

  return (
    <QueryClientProvider client={queryClient}>{children}</QueryClientProvider>
  );
};

export default TanstackProvider;

and I am using it in my layout.tsx file as such:

layout.tsx

import type { Metadata } from "next";
import { Rubik } from "next/font/google";
import "./globals.css";
import CommentContextProvider from "@/context/CommentContext";
import { getComments } from "@/lib/helpers/db-calls";
import prisma from "@/lib/helpers/prisma";
import TanstackProvider from "./_components/providers/TanstackProvider";

const rubik = Rubik({ subsets: ["latin"] });

export const metadata: Metadata = {
  title: "Create Next App",
  description: "Generated by create next app",
};

export default async function RootLayout({
  children,
}: {
  children: React.ReactNode;
}) {
  // const comments = await prisma.comment.findMany();

  return (
    <html lang="en">
      <body className={rubik.className}>
        <TanstackProvider>
          {/* <CommentContextProvider comments={comments}> */}
            {children}
          {/* </CommentContextProvider> */}
        </TanstackProvider>
      </body>
    </html>
  );
}

the commented out section was where I was using react context to manage the state before I tried to implement react query.

I am using next 14.0.4 with the app router.

Any info on what I can do to remedy this would be greatly appreciated.

check function not waiting for response

I am trying to create a telegram bot and this function doesn’t work as intended function checks if the user is new if so then it ask for name and age and it should wait until the user enters the name and then proceed but it doesn’t

async function check(chat_id) {
  const firstText =
    "Hi there! Before you start using the bot, you need to enter the following details: name, age";
  const res = await Subscription.findOne({ chatId: chat_id });

  if (!res) {
    let name;
    let age;

    await bot.sendMessage(chat_id, firstText);
    await bot.sendMessage(chat_id, "Name?");

    await bot.once("message", async (message) => {
      name = message.text.trim().toLowerCase();
    });

    await bot.sendMessage(chat_id, "Age?");
    bot.once("message", async (message) => {
      age = message.text.trim().toLowerCase();
    });

    try {
      // Create a new subscription document in the database
      await Subscription.create({
        chatId: chat_id,
        name: name,
        age: age,
      });

      // Now you can use the captured name and age for further processing
      await bot.sendMessage(
        chat_id,
        "Thanks for providing your details. You are now registered!"
      );
    } catch (error) {
      console.error("Error inserting data:", error.message);
      await bot.sendMessage(chat_id, "Error occurred. Please try again later.");
    }
  } else return;
}

Keep page scroll position of a page in Svelte

I’m using Svelte, and trying to keep the scroll position on a single page such when a user navigates to another page and then navigates back (through back in the browser or the navbar) the page loads and keeps same scroll position.

I’ve tried doing this using a store, and the <svelte:window> element. According to the note here I should use onMount to scroll the page on mount. This is what I’ve tried:

// scrollPosition.ts
import { writable } from 'svelte/store'

export const y = writable(0)

// component.svelte
<script lang="ts">
import { y } from '$lib/stores'
import { onMount } from 'svelte'

onMount(() => {
  scrollTo(0, $y)
})
</script>

<svelte:window bind:scrollY={$y} />
...

I’ve verified the store is updated with scroll position, and when the component mounts it is being reset to 0. So no scroll actually happens on mount.

Any suggestions how to solve this?