Why the values from the input fields are not passing onto the useState values?

I know there is only a slight problem in this code. I’ve been trying to find it but I keep failing, hence I post it here. When I manually add data into the useState variables, signin/ signup buttons are working. But when I remove them and try to get values from the form input fields, it passes no data values into the useStates. why’s that?

import React, { useState } from "react";
import styled from "styled-components";
import logo from "../../assets/logo.svg";
import Input from "./Input";

import { Link, useNavigate } from "react-router-dom";
import { colors } from "../../assets/colorPalette";

import {
  createUserWithEmailAndPassword,
  signInWithEmailAndPassword,
} from "firebase/auth";
import { doc, setDoc } from "firebase/firestore";
import { db, auth } from "../../config/firebaseConfigs";

const SideBar = ({ formType }) => {
  const [fName, setFName] = useState("laoaso");
  const [lName, setLName] = useState("Rage");
  const [mobile, setMobile] = useState("23456752");
  const [email, setEmail] = useState("[email protected]");
  const [password, setPassword] = useState("123123");
  const [confirmPassword, setConfirmPassword] = useState("123123");

  const navigate = useNavigate();

  const handleChange = (e) => {
    const { name, value } = e.target;
    switch (name) {
      case "fName":
        setFName(value);
        break;
      case "lName":
        setLName(value);
        break;
      case "mobile":
        setMobile(value);
        break;
      case "email":
        setEmail(value);
        break;
      case "password":
        setPassword(value);
        break;
      case "confirmPassword":
        setConfirmPassword(value);
        break;
      default:
        break;
    }
  };

  const handleSubmit = async (e) => {
    e.preventDefault();
    console.log(
      "Email:",
      email + "nPassword: ",
      password + "nFirst Name: ",
      fName + "nLast Name: ",
      lName + "nMobile: ",
      mobile + "nConfirm Password: ",
      confirmPassword
    );

    // Validate that all required fields are filled
    if (!email || !password) {
      alert("Please fill in all required fields.");
      return;
    }

    if (password !== confirmPassword) {
      console.log("Passwords do not match");
      return;
    }

    try {
      if (formType === "signin") {
        await signInWithEmailAndPassword(auth, email, password);
      } else {
        const userCredential = await createUserWithEmailAndPassword(
          auth,
          email,
          password
        );

        await setDoc(doc(db, "Patients", userCredential.user.email), {
          email,
          fName,
          lName,
          mobile,
          password,
        });
      }
      navigate("/signin");
    } catch (error) {
      alert("Authentication failed" + error.message);
    }
  };

  return (
    <Container>
      <LogoWrapper>
        <img src={logo} alt="CareBridge-Logo" />
        <h3>
          CARE<span> BRIDGE</span>
        </h3>
      </LogoWrapper>
      <Form onSubmit={handleSubmit}>
        <h3>{formType === "signup" ? "Sign Up" : "Sign In"}</h3>
        {formType === "signup" ? (
          <>
            <Input
              id="fName"
              type="text"
              name="fName"
              value={fName}
              placeholder="First Name"
              onChange={handleChange}
            />
            <Input
              id="lName"
              type="text"
              name="lName"
              value={lName}
              placeholder="Last Name"
              onChange={handleChange}
            />
            <Input
              id="Mobile"
              type="tel"
              name="mobile"
              value={mobile}
              placeholder="Phone Number"
              onChange={handleChange}
            />
          </>
        ) : null}
        <Input
          id="email"
          type="email"
          name="email"
          value={email}
          placeholder="Email Address"
          onChange={handleChange}
        />
        <Input
          id="pswd"
          type="text"
          name="password"
          value={password}
          placeholder="Password"
          onChange={handleChange}
        />
        {formType === "signup" ? (
          <Input
            id="confirmpswd"
            type="text"
            name="confirmPassword"
            value={confirmPassword}
            placeholder="Confirm Password"
            onChange={handleChange}
          />
        ) : null}

        <button type="submit">
          {formType === "signup" ? "Sign up" : "Sign in"}
        </button>
      </Form>
      <div>
        <Terms>
          By signing up, I agree to the Privacy Policy <br /> and Terms of
          Service.
        </Terms>
        <h4>
          {formType === "signup" ? (
            <>
              Already have an account?{" "}
              <span>
                <Link to={"/signin"}>Sign in</Link>
              </span>
            </>
          ) : (
            <>
              New to CareBridge?{" "}
              <span>
                <Link to={"/signup"}>Sign up</Link>
              </span>{" "}
              here.
            </>
          )}
        </h4>
      </div>
    </Container>
  );
};

export default SideBar;

I tried changing useState from userData[] to collecting all input fields separately like i have done in the code.

How to put 2 different emails in CC in Appscripts?

I’m trying to put 2 different emails in CC:, but the second one never goes, any idea what this problem could be?

function enviarEmail() {
  var ss = SpreadsheetApp.getActive()
  const data = ss.getSheetByName('Página 1')


  const emailPessoal = data.getRange('B9').getValue()

  const nomePessoal = data.getRange('B12').getValue()

  const emailIta = data.getRange('B10').getValue()

  const emailLider = data.getRange('B11').getValue()

  var ticket = data.getRange('B13').getValue()

  const emailTI = data.getRange('B15').getValue()

  // Recupere os dados coletados
  const acessos = coletarDados()


  // declaração das variaveis do email de cada item

  var textoNote = ""
  var loginNote = data.getRange('B2')

  var textoRamal = ""
  var loginRamal = data.getRange('B3')

  var textoGmail = ""
  var loginGmail = data.getRange('B4')

  var textoVm = ""
  var loginV = data.getRange('B5')

  var textoSt = ""
  var loginSt = data.getRange('B6')

  var textoVpn = ""
  var loginVpn = data.getRange('B7')


  // Montar o corpo do e-mail
  const subject = nomePessoal

  if (loginNote.getValue() !== '') {
    textoNote = '<b><li> Notebook </li>' +
      'Número - ' + acessos['Notebook'].login + '<br><br>' +
      'Senha - ' + acessos['Notebook'].senha + '<br><br>'
  }

  if (loginRamal.getValue() !== '') {
      'Número - ' + acessos['Ramal'].login + '<br><br>' +
      'Senha - ' + acessos['Ramal'].senha + '<br><br>'
  }

  if (loginGmail.getValue() !== '') {
    textoGmail =
      'Login - ' + acessos['Gmail'].login + '<br><br>' +
      'Senha - ' + acessos['Gmail'].senha + '<br><br>'
  }

  if (loginVm.getValue() !== '') {
    textoVmulti = '<li></li>' +
      'Login - ' + acessos['Mu'].login + '<br><br>' +
      'Senha - ' + acessos['Mu'].senha + '<br><br>'
  }

  if (loginSt.getValue() !== '') {
    textoSt = 
      '<b> Link de acesso: </b> +
      'Login - ' + acessos['ST'].login + '<br><br>' +
      'Senha - ' + acessos['ST'].senha + '<br><br>' +
  }

  if (loginVpn.getValue() !== '') {
    textoVpn = '<li>Acesso VPN (WLAN PRINCIPAL) </a> </li> ' +
      'Login - ' + acessos['VPN'].login + '<br><br>' +
      'Senha - ' + acessos['VPN'].senha + '<br><br>'
  }


  // conecta a assinatura HTML ao e-mail 
  var assinatura = HtmlService.createHtmlOutputFromFile('assinatura')
    .getContent();

  // Faz o a parte inical do e-mail
  let message =
    textoNote +
    textoRamal +
    textoGmail +
    textoVm +
    textoSt +
    textoVpn + '<br><br>' +
    ticket +
    assinatura

// Envia para os e-mails, adiciona o assunto, o nome de e o e-mail de quem via enviar, e tambem adiciona a cópia e o Body da mensagem

  GmailApp.sendEmail([emailPessoal, emailIta], subject, '', { from: '[email protected]', cc: [emailLider, emailTI], name: 'TI', htmlBody: message })
 

}

I already tried to do it like this:

function enviarEmail() {
  var destinatario = "[email protected]";
  var cc1 = "[email protected]";
  var cc2 = "[email protected]";
  var assunto = "Assunto do email";
  var corpoEmail = "Conteúdo do email";

  GmailApp.sendEmail(destinatario, assunto, corpoEmail, {
    cc: cc1 + "," + cc2
  });
}

and

GmailApp.sendEmail([emailPessoal, emailItz], subject, '', { from: '[email protected]', cc: [emailLider, emailTI], name: 'TI', htmlBody: message })

Data still remains in forms

I’m practicing vueJS and IONIC together. I have created a form but data still remains in place and need a refresh to clear them. Where should I take a look? Router, state or components?

App.vue:

<template>
    <ion-app>

        <MainMenu menu_title="Main Menu"/>
        <ion-header :translucent="true" ref="header">
            <MainToolbar/>
        </ion-header>

        <ion-router-outlet id="main-content"/>

    </ion-app>
</template>

<script setup lang="ts">
import { IonApp, IonHeader, IonRouterOutlet } from '@ionic/vue';
import { onMounted } from 'vue';

import MainMenu from '@/components/MainMenu.vue';
import MainToolbar from '@/components/MainToolbar.vue';
import { setTheme, userTheme } from '@/utils/ToggleDark';

// Toggle Dark Theme
onMounted(() => setTheme(userTheme.value));
</script>

File pond not working properly in form repeater

I am using file pond in a repeat form, and if every input form is created correctly, a file pond is also created, but my problem is that in the second or third repeat form, all the previous file ponds are also there. I can not do anything so that they are not displayed
i use blade and livewire with js

create file pond :

                const filepondPlace = document.getElementById('filepond-place')

                let filepondDiv = document.createElement('div')
                filepondDiv.setAttribute('id', row + '-filepond')
                filepondDiv.setAttribute('class', 'filepondDiv')
                filepondDiv.setAttribute('name', 'formRepeater.'+row)
                filepondPlace.appendChild(filepondDiv)

                let input = document.createElement('input')
                input.setAttribute('type', 'file')
                input.setAttribute('multiple', true)
                input.setAttribute('class', 'formRepeater.' + row)
                input.setAttribute('id', 'input' +row)
                input.setAttribute('name', 'formRepeater.'+row)
                filepondDiv.appendChild(input)

                let filePondEvent = new Event('filepond')
                filePondEvent.detail = [{
                    'id': 'input' +row
                }]

and this event :

     FilePond.registerPlugin(FilePondPluginImagePreview, FilePondPluginFileValidateType, FilePondPluginPdfPreview);

      document.addEventListener('filepond',function (event){
          let inputElement =document.getElementById(event.detail[0]['id'])
          const pond = FilePond.create(inputElement, {
                  // acceptedFileTypes: ['image/png'],
                  multiple: true,
                  name: 'filepond'+ inputElement.getAttribute('id'),
                  id : inputElement.getAttribute('id'),
                  maxFileSize: '3MB',
                  minFileSize: '1KB',
 inputElement.getAttribute('id')
              });


      })```

and my blade fie : 
`    <div class="modal fade" id="modalCenter" tabindex="-1" aria-hidden="true" wire:ignore.self>
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header" >
                    <h5 class="modal-title secondary-font" id="modalCenterTitle">اپلود پیوست های مرتبط با مصوبه</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body" id="filepond-place">

                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-label-secondary" data-bs-dismiss="modal">
                        بستن
                    </button>
                </div>
            </div>
        </div>
    </div>`



I want to know only the file pond input in each repeat form

Reset and append new data to bootstrapDualListbox

In create.blade.php I have 2 select fields

First select field is to select a customer,
second select field uses bootstrapDualListbox that displays all cars when create view is returned

I need when a customer has been selected to repopulate the bootstrapDualListbox with cars that only related to that customer

I get in console.log the new options data in json correctly when a customer is selected,
the problem I’m facing is resetting the bootstrapDualListbox and repopulating it with the new data I got after customer selection

HTML:

<div class="card-body">
    <div>
        <select id="customer_cars_duallistbox" name="customer_cars[]" multiple="multiple">
            @foreach($customer_cars $id => $customer_car)
                <option value="{{ $id }}" {{ in_array($id, old('customer_cars', [])) ? 'selected' : '' }}>{{ $customer_car }}</option>
            @endforeach
        </select>
    </div>
</div>

JS:

$(document).ready(function () {
    $("#customer_id").on('change', function(){

        var customer_id = this.value;
        console.log(customer_id)
            
        var customerUrl = "{{ route('admin.user-cars.byCustomer') }}/" + customer_id;

        $.ajax({
            url: customerUrl, 

            success: function(result){


                    var html = '<option value=""></option>';
                    result = jQuery.parseJSON(result);
                    console.log(result);
                   
                    for(var key in result) {
                        html += '<option value="'+key+'">'+result[key]+'</option>';
                        
                    }

                    console.log(html);
                    $('.customer_cars_duallistbox').bootstrapDualListbox('refresh', true);
                    $(".customer_cars_duallistbox").append(html);

                }
            });

        });
    });

Also tried

 $("#customer_cars_duallistbox").html(html);
 $('#customer_cars_duallistbox').val('');

Nothing changes at all,

If I try appending the new customer filtered data to a select2 field it works fine, but how to correctly implement this for bootstrapDualListbox?

Any help appreciated.

Can I filter a RSS stream for a keyword and if found, hide the stream on website?

I was looking this up but couldn’t find this question before. I have a RSS stream on my website which shows weather alerts. In case there are no alerts it says : “No alerts in effect”

Is it possible to filter this with a JavaScript and if found hide that script on the website?

Here is the stream and how its displayed on the website. I basically pasted this in the website code.

I am not really into JavaScript, just start to learn it and it seems a little difficult.

<div align="center"> <rssapp-list id="e9zUmczW5YQD4WEP"></rssapp-list><script src="https://widget.rss.app/v1/list.js" type="text/javascript" async></script> </div>

So that result of the stream is shown perfectly in place. I Just would like to hide it when there are no active alerts.

How can I wrap unwrapped data inside div? [closed]

I have an HTML block such as the following example. It’s made up of 4 messages, each starting with “MSG|”. The first and last are nicely wrapped in their own divs, however the middle 2 are not, they’re just plain text inside “container”.

Is there a nice way to wrap the 2 middle blocks “MSG|5 … DAT|9|10” & “MSG|11 … 14” in divs? I’m thinking a .replace()s solution might be the most straightforward way, but there must be a nicer solution that’s not popping in to my brain right now.

<div id="container">
<div>
MSG|1|2
DAT|3|4
</div>
MSG|5|6
DAT|7|8
DAT|9|10
MSG|11|12
DAT|13|14
<div>
MSG|15|16
DAT|17|18
</div>
</div>

How to design a good algorithm? [closed]

can you give me some ideas??? I want to make a text-based supermarket simulator game in browser as a first full stack project. A game where you manage stock, sells, finances etc.

My QUESTION is before even writing code:

How can I write some good algorithms for it? Let me explain. I’ll need algorithms for how many people
come everyday and what products they buy. Is there a smarter way to write algorithms like these ones
without just using a bunch of random functions? And to make them adaptable, like if the store gets bigger, more people will come.

Don’t hesitate to give me your past experiences on how you designed an algorithm.

I’m quite a beginner so I don’t know if what I’m saying makes sense for more experienced programmers, so just ask where I can be more explicit, THANK YOU!

(I did not try anything right now, I’m kind of stuck. I can only thing of Random functions.)

Cloudflare Script Injection into WooCommerce PDF Catalogs – How to Prevent?

I’m working with a WooCommerce store on WordPress, and we have a PDF catalog plugin that generates PDFs based on product categories. We’ve noticed an unexpected Cloudflare script at the bottom of our generated PDFs. The script looks like a Cloudflare challenge script and appears as follows on the last page of every PDF. This has started happening since we started using Cloudflare. Any help to why this might be happening would be really appreciated. Thank you.
image of problem

I considered whitelisting our server IP to try see if the issue persists but this would also slow down all requests made back to our server so wouldnt be a great solution.

How to configure service worker in vitejs app?

This is my Vite config:


   VitePWA({
        strategies: 'injectManifest',
        srcDir: 'src',
        filename: 'my-sw.ts',
        injectRegister: 'auto',
        registerType: "autoUpdate",
        workbox: {
          globPatterns: ['**/*.{js,css,html,ico,png,svg}']
        },
        devOptions: {
          enabled: true,
        },

        // TODO: add specific content to align with app requirements.
        manifest: {
         //
        },
      })

This is my service worker:

import { precacheAndRoute } from "workbox-precaching";
import { clientsClaim } from "workbox-core";

declare let self: ServiceWorkerGlobalScope

self.addEventListener("message", event => {
  if (event.data && event.data.type === "SKIP_WAITING") self.skipWaiting();
});

precacheAndRoute(self.__WB_MANIFEST);
self.skipWaiting();
clientsClaim();

Taken from docs.
When I run npm run build service worker is copied to public directory. Hence it works as expected, but I don’t know how to make app work when offline.

I was trying this example but when I go offline – it does not seem to work.

What should be done to make app work offline? How I can trigger different service workers events to test and debug it? How to test it in development mode? Could you please point me an appropriate section in documentation? I went through docs but I might miss something.

Chrome extension declarativeNetRequest

I am currently working on migrating a chrome extension from manifest_version 2 to v3. I did most of the changes but I am stuck with declarativeNetRequest. There is a scenario where we need to redirect the user based on the URL pattern.
For Ex: when a use click on the app in the extension popup and the URL is let’s say https://xyxinc.xyx.com/start/12345 then it should be transformed to https://xyxinc.xyx.com/start/12345?plugin=3.1.1
and when the app has passed the authentication phase then it will be automatically moved to the respective app URL which is being handled automatically.

There are two problems I am facing here:

  1. When I am clicking on the app in the portal then I am not getting how to get the URL of the app i.e., https://xyxinc.xyx.com/start/12345 as it was pretty handy to get the url in the callback passed to webRequest API but in decalarativeNetRequest we don’t have such feature.
  2. Will the rule kicks in always as we navigate to the URLs or it will be applied only once at the beginning? If it is applied once then how can I redirect the user when there are dynamic redirect URLs.
  3. Also, for manifest v3 can we use declarativeNetRequest and webRequest APIs together as per use cases or only the declarativeNetRequest will be applicable?

Please help me as I tried searching over internet but didn’t get accurate information

Thnaks in advance

Displaying a custom woocommerce cart fee based on a custom datepicker field selection

Party Rental Equipment website. Using the JQuery datepicker in 3 woocommerce_form_field, one for Event Date, One for Delivery Date, and one for Pickup Date. I am trying to charge a $440 extra fee if the user selects a Sunday for Delivery Date or Pickup Date. In this datepicker Sunday is the first day of the week, Day 0.

The fee appears after the customer checkouts and receives the order meta or order email, but I can’t get it to show on the checkout page on ajax update, which is important because i want them to know how much it costs before they checkout. I am hoping someone out there would be generous enough to help me with this, 🙂

Here’s the code i am using – as mentioned the fees are visible when the checkout is processed but not on the actual checkout page, even after update_cart. this is in my child theme functions.php

//DATEPICKER STUFF
//
//
//
// enqueue jquery script
function enqueue_datepicker_scripts() {
    // Enqueue jQuery UI
    wp_enqueue_script('jquery-ui-datepicker');
}
add_action('wp_enqueue_scripts', 'enqueue_datepicker_scripts');

// Enqueue jquery options
function enqueue_datepicker_script() {
    ?>
    <script>
    jQuery(function ($) {
        // Datepicker options
        var datepickerOptions = {
            dateFormat: 'mm/dd/yy',
            minDate: '+3d', // Minimum date is today + 3 days
            firstDay: 0, // Start week with Sunday
            onSelect: function (dateText, inst) {
                setTimeout(function () {
                    $('body').trigger('update_checkout');
                }, 1);
            }
        };

        // Event Date
        $('#event_date').datepicker($.extend({}, datepickerOptions));

        // Delivery Date
        $('#delivery_date').datepicker($.extend({}, datepickerOptions));

        // Pickup Date
        $('#pickup_date').datepicker($.extend({}, datepickerOptions));
    });
    </script>
    <?php
}
add_action('wp_footer', 'enqueue_datepicker_script');

// Add datepicker to checkout fields
function custom_add_date_picker_fields($checkout) {
    echo '<div id="custom_date_picker"><h2>' . __('Delivery and Pickup Details') . '</h2>';

    // Event Date
    woocommerce_form_field('event_date', array(
        'type' => 'text',
        'class' => array('form-row-wide datepicker'),
        'label' => __('Event Date'),
        'required' => true,
        'default' => date('m/d/Y', strtotime('+3 days')), // Default is 3 days from today
        'custom_attributes' => array(
            'min' => date('m/d/Y', strtotime('+3 days')), // Minimum date is 3 days from today
            'max' => date('m/d/Y', strtotime('+2 years')), // Maximum date is 2 years from today
        ),
    ), $checkout->get_value('event_date'));

    // Delivery Date
    woocommerce_form_field('delivery_date', array(
        'type' => 'text',
        'class' => array('form-row-wide datepicker'),
        'label' => __('Delivery Date'),
        'required' => true,
        'default' => date('m/d/Y', strtotime('+2 days')), // Default is 1 day before the event date
    ), $checkout->get_value('delivery_date'));

    // Pickup Date
    woocommerce_form_field('pickup_date', array(
        'type' => 'text',
        'class' => array('form-row-wide datepicker'),
        'label' => __('Pickup Date'),
        'required' => true,
        'default' => date('m/d/Y', strtotime('+4 days')), // Default is 1 day after the event date
    ), $checkout->get_value('pickup_date'));

    echo '</div>';
}
add_action('woocommerce_before_order_notes', 'custom_add_date_picker_fields');


function custom_process_date_picker_fields() {
}
add_action('woocommerce_checkout_process', 'custom_process_date_picker_fields');

// save to order meta
function custom_update_date_picker_fields($order_id) {
    // Save Event Date
    if (!empty($_POST['event_date'])) {
        update_post_meta($order_id, 'Event Date', sanitize_text_field($_POST['event_date']));
    }

    // Save Delivery Date
    if (!empty($_POST['delivery_date'])) {
        update_post_meta($order_id, 'Delivery Date', sanitize_text_field($_POST['delivery_date']));
    }

    // Save Pickup Date
    if (!empty($_POST['pickup_date'])) {
        update_post_meta($order_id, 'Pickup Date', sanitize_text_field($_POST['pickup_date']));
    }
}
add_action('woocommerce_checkout_update_order_meta', 'custom_update_date_picker_fields');

// Add fee with standard tax
function custom_add_sunday_delivery_fee() {
    // Check if delivery date is set
    if (isset($_POST['delivery_date'])) {
        $delivery_date = sanitize_text_field($_POST['delivery_date']);
        $delivery_day = date('w', strtotime($delivery_date));

        // Check if delivery date is Sunday
        if ($delivery_day == 0) { // Sunday
            WC()->cart->add_fee(__('Sunday Delivery', 'woocommerce'), 440, true, 'standard');
        }
    }
}
add_action('woocommerce_cart_calculate_fees', 'custom_add_sunday_delivery_fee', 10);

// pickup fee
function custom_add_sunday_pickup_fee() {
    // Check if pickup date is set
    if (isset($_POST['pickup_date'])) {
        $pickup_date = sanitize_text_field($_POST['pickup_date']);
        $pickup_day = date('w', strtotime($pickup_date));


        // Check if pickup date is Sunday
        if ($pickup_day == 0) { // Sunday
            WC()->cart->add_fee(__('Sunday Pickup', 'woocommerce'), 440, true, 'standard');
        }
    }
}
add_action('woocommerce_cart_calculate_fees', 'custom_add_sunday_pickup_fee', 10);

Drag and Drop File is not sending data to flask

I have the following button which supports both file browsing and drag drop.
Im not differentiating between dropped images and browsed images.
Still only the browsed images are getting uploaded, not the dropped one.

My Javascript code :

photoinput = document.querySelector(".photo-div input");
imagesArray = [];

photoinput.addEventListener("change",()=>{
    const files = photoinput.files;
    for(let i = 0; i < files.length; i++) imagesArray.push(files[i]);
    displayImages();
})

photoinput.addEventListener("drop", (e) => {
    e.preventDefault();
    const files = e.dataTransfer.files;

    for (let i = 0; i < files.length; i++) {
        if (!files[i].type.match("image")) continue;
        imagesArray.push(files[i]);
    }

    displayImages();
});

photoinput.addEventListener("dragover", (e) => {
    e.preventDefault();
});

My HTML Code :

<div class="photo-div">
                <p><span class="browse">Browse or Drag and Drop Here</span></p>
                <input type="file" class="file" name="image" multiple="multiple" accept="image/png, image/jpeg, image/jpg" value="Drag and Drop Here">   
</div>

My python code:

if request.method == 'POST':

        print((request.files))
        print(len(request.files))

        if 'image' in request.files:
            images = request.files.getlist('image')

Exact Issues I am facing:

  1. Dropped images is getting received as empty file in flask
  2. Dropping and Browsing are not working simulateneously (Only browsing works)

Typeerror: Failed to execute fetch on window. Invalid name

I am trying to hit twitter’s graphql api through the network tab(obviously on same origin)

Here’s my current implementation:

// Example POST method implementation:
async function getData(username, data = {}) {
    let URL = `https://api.twitter.com/graphql/k5XapwcSikNsEsILW5FvgA/UserByScreenName?variables={"screen_name":"${username}","withSafetyModeUserFields":true}&features={"hidden_profile_likes_enabled":true,"hidden_profile_subscriptions_enabled":true,"responsive_web_graphql_exclude_directive_enabled":true,"verified_phone_label_enabled":true,"subscriptions_verification_info_is_identity_verified_enabled":true,"subscriptions_verification_info_verified_since_enabled":true,"highlights_tweets_tab_ui_enabled":true,"responsive_web_twitter_article_notes_tab_enabled":true,"creator_subscriptions_tweet_preview_api_enabled":true,"responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,"responsive_web_graphql_timeline_navigation_enabled":true}&fieldToggles={"withAuxiliaryUserLabels":false}`
    // Default options are marked with *
    const response = await fetch(URL, {
        method: "GET", // *GET, POST, PUT, DELETE, etc.
        mode: "cors", // no-cors, *cors, same-origin
        cache: "no-cache", // *default, no-cache, reload, force-cache, only-if-cached
        credentials: "same-origin", // include, *same-origin, omit
        headers: {
            "Content-Type": "application/json",
            ":path": `/graphql/k5XapwcSikNsEsILW5FvgA/UserByScreenName?variables={"screen_name":"${username}","withSafetyModeUserFields":true}&features={"hidden_profile_likes_enabled":true,"hidden_profile_subscriptions_enabled":true,"responsive_web_graphql_exclude_directive_enabled":true,"verified_phone_label_enabled":true,"subscriptions_verification_info_is_identity_verified_enabled":true,"subscriptions_verification_info_verified_since_enabled":true,"highlights_tweets_tab_ui_enabled":true,"responsive_web_twitter_article_notes_tab_enabled":true,"creator_subscriptions_tweet_preview_api_enabled":true,"responsive_web_graphql_skip_user_profile_image_extensions_enabled":false,"responsive_web_graphql_timeline_navigation_enabled":true}&fieldToggles={"withAuxiliaryUserLabels":false}

`,
            ":authority": "api.twitter.com",
            ":method": "GET",
            ":scheme": "https",
            "Authorization": "Bearer AAAAAAAAAAAAAAAAAAAAANRILgAAAAAAnNwIzUejRCOuH5E6I8xnZz4puTs%3D1Zv7ttfk8LF81IUq16cHjhLTvJu4FA33AGWWjCpTnA",
            "Cookie": `guest_id_marketing=v1:170955125343839663; guest_id_ads=v1:170955125343839663; guest_id=v1:170955125343839663; gt=1764611971050074353; _ga=GA1.2.251089784.1709551255; _gid=GA1.2.393957230.1709551255; personalization_id="v1_5jbQDTm8Tn2sQ/f9diPocA=="
`,
            "Origin": "https://twitter.com",
            "Referer": "https://twitter.com",
            "X-Client-Transaction-Id": "I7fMTBcu/4HmKfngKEMY6kPjahaJoBRzqcr/bTYgBPINSk5CBpY1sDLiD3RBiJlAp0RotSI7wGYBtp0x28iZw/JR986wIg",
            "X-Guest-Token": "1764611971050074353"

        },
        redirect: "follow", // manual, *follow, error
        referrerPolicy: "strict-origin-when-cross-origin", // no-referrer, *no-referrer-when-downgrade, origin, origin-when-cross-origin, same-origin, strict-origin, strict-origin-when-cross-origin, unsafe-url

    });
    return response.json(); // parses JSON response into native JavaScript objects
}

getData("sama").then((data) => {
    console.log(data); // JSON data parsed by `data.json()` call
});

All this is being done on a public profile page such as https://twitter.com/sama

Its giving me this error

Promise {<rejected>: TypeError: Failed to execute 'fetch' on 'Window': Invalid name

I didn’t copy all the headers just the ones I thought were important

And I decoded the urls and cookie strings from the network tab(so no wrong chars in the request probably)

What am I doing wrong here?

Also all of the tokens etc are safe to be public as it was all on an unlogged incognito window!