Image is not being submitted to PHP script when using “Drag & Drop” Image Upload Form

Im trying to upload and submit images using a drag and drop based image upload form , which has both the feature-
1.Browse button and select image (traditional way) and
2.(dragging image to the form area)

Drag and Drop Form

When Im uploading the image through the “Browse File” button and then submitting(compress here) its working fine.But when Im dragging an image into the droparea and clicking on submit (compress here) , the image is not being submited to the PHP script underlying. Where I need to make changes to achieve it ?

I have tried by dynamically changing the value of the input field of the html with id “imageField” through javascript but it didn’t work.

You can see the PHP script here for reference.

script.js and index.html as followed:

//selecting all required elements
const dropArea = document.querySelector(".drag-area"),
dragText = dropArea.querySelector("header"),
button = dropArea.querySelector("button"),
input = dropArea.querySelector("input");
let file; //this is a global variable and we'll use it inside multiple functions

button.onclick = ()=>{
  input.click(); //if user click on the button then the input also clicked
}

input.addEventListener("change", function(){
  //getting user select file and [0] this means if user select multiple files then we'll select only the first one
  file = this.files[0];
  dropArea.classList.add("active");
  showFile(); //calling function
});


//If user Drag File Over DropArea
dropArea.addEventListener("dragover", (event)=>{
  event.preventDefault(); //preventing from default behaviour
  dropArea.classList.add("active");
  dragText.textContent = "Release to Upload File";
});

//If user leave dragged File from DropArea
dropArea.addEventListener("dragleave", ()=>{
  dropArea.classList.remove("active");
  dragText.textContent = "Drag & Drop to Upload File";
});

//If user drop File on DropArea
dropArea.addEventListener("drop", (event)=>{
  event.preventDefault(); //preventing from default behaviour
  //getting user select file and [0] this means if user select multiple files then we'll select only the first one


  file = event.dataTransfer.files[0];
  name = event.dataTransfer.files[0].name;

  showFile(); //calling function
});

function showFile(){
  let fileType = file.type; //getting selected file type
  let validExtensions = ["image/jpeg", "image/jpg", "image/png"]; //adding some valid image extensions in array
  if(validExtensions.includes(fileType)){ //if user selected file is an image file
    let fileReader = new FileReader(); //creating new FileReader object
    fileReader.onload = ()=>{
      let fileURL = fileReader.result; //passing user file source in fileURL variable
      let imgTag = `<img src="${fileURL}" alt="">`; //creating an img tag and passing user selected file source inside src attribute
      dropArea.innerHTML = imgTag; //adding that created img tag inside dropArea container
    }
    fileReader.readAsDataURL(file);
  }else{
    alert("This is not an Image File!");
    dropArea.classList.remove("active");
    dragText.textContent = "Drag & Drop to Upload File";
  }
}

var form = document.getElementById("imageForm");
document.body.appendChild(form);
document.getElementById("compress").addEventListener("click", function () {
  //console.log(document.getElementById("imgField").value);
  form.submit();
});
<!DOCTYPE  html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Drag & Drop or Browse: File Upload | CodingNepal</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="https://kit.fontawesome.com/a076d05399.js"></script>
</head>


<body>
  <div class="drag-area">
    <div class="icon"><i class="fas fa-cloud-upload-alt"></i></div>
    <header>Drag & Drop to Upload File</header>
    <span>OR</span>
    <button>Browse File</button>
    <form id="imageForm" method="post" action="compressImage.php" enctype="multipart/form-data">
      <input id="imgField" name="image" type="file" hidden>
    </form>
  </div>

  <button id="compress">Compress</button>
  <script src="js/script.js"></script>

</body>


</html>

creating toggling with JSON

I have this particular JSON with two keys (“cars”,”others”).
How can I create toggling in my website using HTML/CSS/javacript such that if I click on on “cars” it should display the car.items (small-vehicle,large vehicle) in the webpage and the texts should be of color:red and if I click on “others” it should hide the car.items and display others.items in blue colour.

Please help me with this.
Note: the toggle can be button or a link thats fine as long as it is toggling properly.

…

{
"cars": {
"items": ["small-vehicle","large-vehicle"],
"color": "red"
},

"others": {
"items": ["swimming pool","plane","ship",],
"color": "blue"
 }
}

…

JS: how to not overuse try/catch?

I can’t tell if I overuse try/catch. I feel like when in doubt, I always end up using it. If there is every an API call, I wrap all the code in a try/catch. Is there a rule of thumb to follow?

for example, in this function:

async isValidName(name: string): boolean {
    const baseURL = SERVER_INFO.url

    const config: RequestInit = {
        method: "get",
        headers: {
            Authorization: 'xxxxx,
            "X-Api-key": SERVER_INFO.API_KEY
        }
    };

    const response = await fetch(`${baseURL}/v1/font_catalog`, config );
    const { library } = await response.json();

    return library;
}

I just changed it to wrap the whole thing in a try catch. Is this an improper way to use it?

async isValidName(name: string): boolean {
   try {
       const baseURL = SERVER_INFO.url

       const config: RequestInit = {
           method: "get",
           headers: {
               Authorization: 'xxxxx,
               "X-Api-key": SERVER_INFO.API_KEY
           }
       };

       const response = await fetch(`${baseURL}/v1/font_catalog`, config );
       const { library } = await response.json();

       return library;
   } catch(e) {
      throw new Error(e)
   }
}

Problem with pass props from an js array to MUI Item as an link | Type Error: (items.map is not a function)

as I mention in Topic

I got a problem with set a href link and passing it to the mobile, desktop menu. Never had this issue with semantic HTML elements, but I always struggle when I try to pass it to react components for pre-prepared elements.

Did anyone struggle with that before?
Maybe can someone share with me any tutorial or docs on how to inject an array in this kind of element as a map.

Here’s the pure code copied
from the newest MUI React Library with added by me array named [items]

// array
const [items] = ([
  {
    name: 'John',
    href: 'https://google.com'
  }
]);

function DrawerAppBar(props) {
  const { window } = props;
  const [mobileOpen, setMobileOpen] = React.useState(false);

  const handleDrawerToggle = () => {
    setMobileOpen(!mobileOpen);
  };

  // mobile menu
  const drawer = (
    <Box onClick={handleDrawerToggle} sx={{ textAlign: 'center' }}>
      <Typography variant="h6" sx={{ my: 2 }}>
        Logo
      </Typography>
      <Divider />
      <List>
        {items.map(item => (
          <ListItem key={item} disablePadding>
            <ListItemButton component="a" href={item.href} sx={{ textAlign: 'center' }}>
                <ListItemText primary={item.name} />
            </ListItemButton>
          </ListItem>
        ))}
      </List>
    </Box>
  );

  const container = window !== undefined ? () => window().document.body : undefined;

  // desktop menu
  return (
    <Box sx={{ display: 'flex' }}>
      <AppBar component="nav">
        <Toolbar>
          <IconButton
            color="inherit"
            aria-label="open drawer"
            edge="start"
            onClick={handleDrawerToggle}
            sx={{ mr: 2, display: { sm: 'none' } }}
          >
            <MenuIcon />
          </IconButton>
          <Typography
            variant="h6"
            component="div"
            sx={{ flexGrow: 1, display: { xs: 'none', sm: 'block' } }}
          >
            Logo
          </Typography>
          <Box sx={{ display: { xs: 'none', sm: 'block' } }}>
            {items.map(item => (
              <Button key={item.name} sx={{ color: '#fff' }}>
                {item.name}
              </Button>
            ))}
          </Box>
        </Toolbar>
      </AppBar>
      <Box component="nav">
        <Drawer
          container={container}
          variant="temporary"
          open={mobileOpen}
          onClose={handleDrawerToggle}
          ModalProps={{
            keepMounted: true, // Better open performance on mobile.
          }}
          sx={{
            display: { xs: 'block', sm: 'none' },
            '& .MuiDrawer-paper': { boxSizing: 'border-box', width: drawerWidth },
          }}
        >
          {drawer}
        </Drawer>
      </Box>
    </Box>
  );
}

DrawerAppBar.propTypes = {
  /**
   * Injected by the documentation to work in an iframe.
   * You won't need it on your project.
   */
  window: PropTypes.func,
};

export default DrawerAppBar;

And here’s the error from Console in Browser

Navbar.jsx:44 Uncaught TypeError: items.map is not a function
    at DrawerAppBar (Navbar.jsx:44:1)
    at renderWithHooks (react-dom.development.js:16175:1)
    at mountIndeterminateComponent (react-dom.development.js:20913:1)
    at beginWork (react-dom.development.js:22416:1)
    at HTMLUnknownElement.callCallback (react-dom.development.js:4161:1)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:4210:1)
    at invokeGuardedCallback (react-dom.development.js:4274:1)
    at beginWork$1 (react-dom.development.js:27405:1)
    at performUnitOfWork (react-dom.development.js:26513:1)
    at workLoopSync (react-dom.development.js:26422:1)

How to create many arrays with maximum values?

I want to develop a function that receives many strings, maybe 10.000 records and split all values in small arrays with maximum size of 200 records per array, so in this case i want to develop a function that returns 50 arrays with 200 records

Is there any standard lib or a good way to do that in javascript?

vuejs new tab same page previous tab buttons and navbar disappear

I have a vuejs app that loads a navigation bar and some buttons. By default the buttons and the navbar are hidden and depending on your access it will show them to you or not.

Now that part is working ‘fine’ my problem here is that if I open a new tab on the same browser and go to the same page, the new tab gets loaded just fine but the previous one ‘refreshes’ and looses the navbar and the buttons. Is like if the new tab ‘stole’ the permissions from the previous one.

what could be causing this behaviour and/or how to fix it?

thank you

adding mouseover event to img element doesn’t work

this is my html

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
    <link href="style.css" rel="stylesheet" type="text/css" />
    <script src="script.js"></script>
  </head>
  <body onload="load();">
    <img src="img1.png">
    <img src="img2.png">
    <img class="img3" src="img3.png">
  </body>
</html>

And I want the 3rd image to go to the left when mouse is over it. (It has position: absolute; on it) using this js code

let img;
function load(){
  img = document.querySelector(".img3");
  img.addEventListener("mouseover", mouseover);
}
function mouseover(){
  img.style.left = "0px";
}

but mouseover never gets called. (Checked with logging)

Why using Animejs Timeline triggering ‘Cannot read properties of undefined’ error?

I was trying to create an animation with keyframes, but it has annoying delays that cannot be turned off. But when I switched to Timeline, this error appeared:
screenshot

It seems like the problem is in the library file, but any other feature works properly.
Here is the code:

    let attacked = document.getElementsByClassName("opponents_card")[0];

    var pos1 = attacked.getBoundingClientRect();
    var pos2 = attacker.getBoundingClientRect();

    let tl = anime.timeline({
        duration: 1000,
        easing: 'easeInShine'
    });

    tl.add({
        targets: attacker,
        translateY: 20
    }).add({
        targets: attacker,
        translateX: pos1.left - pos2.left,
        translateY: pos1.left - pos2.left
    });
}```

Check if a Twitch Stream Is Live Using node js

I don’t know how to combine them.
I made a code by referring to the link below.
Please Help me…

Android – Checking if a twitch stream is online

Is There Any Way To Check if a Twitch Stream Is Live Using Python?

setting

export const CHANNEL_NAME = ["daXXXXXX", "gmXXXXXXX"];
export const OAUTH_TOKEN = 'oauth:bn1rXXXXXXXXXXXXXXXXX';
export const CLIENT_ID = 'bxqtXXXXXXXXXXXXXXXXX';
export const BOT_USERNAME = 'gaXXXXt';

my code

async function test2() {
    var theUrl = `https://api.twitch.tv/kraken/streams/${CHANNEL_NAME[0]}`
    var headers = {
        "Client-ID": CLIENT_ID

    };
    fetch(theUrl, headers).then(data =>{
        console.log(data)
    })
  }
test2()

debug data

Response {
  size: 0,
  timeout: 0,
  [Symbol(Body internals)]: {
    body: PassThrough {
      _readableState: [ReadableState],
      _events: [Object: null prototype],
      _eventsCount: 5,
      _maxListeners: undefined,
      _writableState: [WritableState],
      allowHalfOpen: true,
      [Symbol(kCapture)]: false,
      [Symbol(kCallback)]: null
    },
    disturbed: false,
    error: null
  },
  [Symbol(Response internals)]: {
    url: 'https://api.twitch.tv/kraken/streams/#daXXXXXX',
    status: 400,
    statusText: 'Bad Request',
    headers: Headers { [Symbol(map)]: [Object: null prototype] },
    counter: 0
  }
}

How do I make an Array for my script with 2 different labels so I can id the game name and url to load it in the same page?

>  <div class="gameslist">
>           <h1>Action Games</h1>
>           <button id="https://theadvancedsociety-tam.tbt.mx/tam-run3/" onClick="reply_click(this.id)">Run 3</button><br>
>           <button id="https://bigfoot9999.github.io/Slope-Game/" onClick="reply_click(this.id)">Slope Game</button><br>
>       
>           <h1>Puzzle & Strategy Games</h1>
>           <h1>Skill Games</h1>
>           <h1>Retro</h1>
>           <h1>Shooter Games</h1>
>           <h1>Other</h1>
>           <script type="text/javascript">
>       function reply_click(clicked_id){
>           console.log(clicked_id);
>               var urlObj = new window.URL(window.location.href);
>               var url = clicked_id;
>               if (url) {
>                 var win;
>                 document.querySelector('button').onclick = function() {
>                   if (win) {
>                     win.focus();
>                   } else {
>                     win = window.open();
>                     win.document.body.style.margin = '0';
>                     win.document.body.style.height = '100vh';
>                     var iframe = win.document.createElement('iframe');
>                     iframe.style.border = 'none';
>                     iframe.style.width = '100%';
>                     iframe.style.height = '100%';
>                     iframe.style.margin = '0';
>                     iframe.src = url;
>                     win.document.body.appendChild(iframe);
>                   }
>                   document.querySelector('button').style.background = '#00000';
>                 };
>               }  
>       }
>     </script>      
>         </div>
> 

How do I get the 2nd button to load the script and load the correct url every time, it seems like the button does not work the first time
the user presses it? Also, there must be a better way to do this with
arrays, and ive never learned about arrays so I need help. Thanks for your help,
Bigfoot9999

Custom Request Headers within TestCafe are not displayed

I have tried a handful of different things and bounced between different suggestions on what could be the problem without any luck. Ultimately I need to test certain aspects of an application that is behind a feature flag which can be accessed with request headers.

I may be trying to accomplish something that isn’t possible with this implementation, but I have attached my code sample below, and the logs generated below that. I expected the added header to be present in the log output.

Code:


class myRequestHook extends RequestHook {
  constructor () {
    super()
  }

  async onRequest (e) {
    e.requestOptions.headers['test-header'] = 'test-value'
  }

  async onResponse (e) {

  }
}

const customHook = new myRequestHook()
const customLogger = RequestLogger('http://example.com', { logRequestHeaders: true })

fixture ('Request fixture')
  .page('http://example.com/')
  .requestHooks( [ customLogger, customHook ])

test('Request test', async () => {
  console.log(customLogger.requests[0].request.headers)
})

Logs:

{
  host: 'example.com',
  connection: 'keep-alive',
  'sec-ch-ua': '" Not A;Brand";v="99", "Chromium";v="102", "Google Chrome";v="102"',
  'sec-ch-ua-mobile': '?0',
  'sec-ch-ua-platform': '"macOS"',
  'upgrade-insecure-requests': '1',
  'user-agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/102.0.5005.115 Safari/537.36',
  accept: 'text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.9',
  'sec-fetch-site': 'same-origin',
  'sec-fetch-mode': 'navigate',
  'sec-fetch-dest': 'document',
  'accept-encoding': 'gzip, deflate, br',
  'accept-language': 'en-US,en;q=0.9'
}