Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

215
Visualizações
Posting Form Data in Javascript with Fetch - Bug

I'd like to start by mentioning that I'm using vanilla Javascript and PHP, no jquery. The code that I have posted below is just a fragment. I have not included the PHP file or other code in javascript.

Now, the problem I am having is that no other code besides the form data post runs whenever I click my save button and activate the event. I have a console log at the beginning and end of the event to test if other code runs, and it never does. The form data, in this case a picture, gets posted to the PHP rest API file and stored in a folder as it should, but I do not receive a response in JSON from the PHP file that it is posted to, and my biggest problem is that no other code besides the post request runs in the event of the javascript code. Neither of the console.logs (test 1 and test 2) will appear.

When I test the post request with any other type of data, for instance, JSON, everything works perfectly. All of the code in the event runs, and I can receive responses in JSON from the same PHP file that the request was made to. There's something about posting form data that creates this bug. I hope that I have explained this clearly enough. Thank you for any assistance.

save_bg_btn.addEventListener('click', save_background_picture);

async function save_background_picture(){

    console.log("test 1");

    const formData = new FormData();
    const save_files_background_pic = file_bg_pic.files[0];
    const url = 'http://localhost/test/background-cover.php';

    formData.append("file_bg_pic", save_files_background_pic);

    await post_formdata_request(url, formData)
        .then(data =>{ 
            console.log(data);
        })
        .catch(err => console.log(err));
    
     console.log(test 2);

}


function post_formdata_request(url, formData){

    return new Promise((resolve, reject) => {
        
        fetch(url, {
            method: 'POST',
            body: formData
        })
        .then(res => res.json())
        .then(data => resolve(data))
        .catch(err => reject(err));
    });
}
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

Assuming this button is in a form, I think you need to add preventDefault() for the click event otherwise the form will submit and refresh the page. Also, fix the second console.log because that was breaking my tests until I noticed it as well.


async function save_background_picture(e){
    e.preventDefault();
    
    // ...rest of the code

    console.log("test 2");  // <--- needed quotes
}
about 4 years ago · Juan Pablo Isaza Relatório

0

html file: test-fetch.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <form id="myForm">
        <input type="file" id="inpFile">
    </form>
</body>

<script>

    const inpFile = document.getElementById('inpFile');
    const myForm = document.getElementById('myForm');

    myForm.addEventListener('change', inpFunction);

    async function inpFunction(e){
        e.preventDefault();

        const endpoint = "http://localhost/php-practice/test-fetch.php";
        const formData = new FormData();
        
        formData.append('inpFile', inpFile.files[0]);

        fetch(endpoint, {
            method: 'post',
            body: formData
        })
        .catch(err => console.log(err));
    }
</script>
</html>

And this is the php file: test-fetch.php

<?php

    $file = $_FILES['inpFile'];

    $fileName = $_FILES['inpFile']['name'];
    $fileTmpName = $_FILES['inpFile']['tmp_name'];
    $fileSize = $_FILES['inpFile']['size'];
    $fileError = $_FILES['inpFile']['error'];
    $fileType = $_FILES['inpFile']['type'];

    $fileExt = explode('.', $fileName);
    $fileActualExt = strtolower(end($fileExt));

    $allowed = array('jpg', 'jpeg', 'png', 'pdf');
    if(in_array($fileActualExt, $allowed)){
        if($fileError === 0){
            if($fileSize < 2000000){
                $fileNameNew = uniqid('', true).".".$fileActualExt;

                $fileDestination = 'images/'.$fileNameNew;

                move_uploaded_file($fileTmpName, $fileDestination);
            }else{
                echo "Your file is too large!";
            }
        }else{
            echo "There was an error uploading your file!";
        }
    }else{
        echo "You cannot upload files of this type!";
    }

    echo 'Success';
?>

Now, if you add any other code, such as a console log inside the function "inpFunction" it will not run. The only code that will run will be the fetch posting the form data to the php file. This problem is really baffling me.

edit: the php file requires a folder called "images" as that is the path destination of any pictures being posted.

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda