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

111
Visualizações
fetch wrongly double inserts into database

I'm using fetch to send data to a PHP script. Only Problem is that it inserts empty data first and then the correct one. I'm sending a JSON string which then gets decode with PHP.

I've tested the script with Postman and it works fine there.

Java-Script Code:

async function uploadImage() {
      let url = "http://localhost/upload_image.php";
      navigator.geolocation.getCurrentPosition(writePosition);
      let dataJSON = {"Koordinate_X":3, "Koordinate_Y":1, "Kategorie":1, "Bild":"Es klappt aus der App"};

      fetch(url, {
        method: 'POST', // or 'PUT'
        /*headers: {
          'Content-Type': 'application/json',
        }, REMOVED*/
        body: JSON.stringify(dataJSON)
      })
    };

HTML Code:

<button on:click={uploadImage}>Upload</button>

PhP Code:

<?php 
header('Access-Control-Allow-Origin:  http://localhost:5173');
header('Access-Control-Allow-Headers:  Content-Type, X-Auth-Token, Authorization, Origin');
header('Access-Control-Allow-Methods:  POST, PUT');

$data = json_decode(file_get_contents('php://input'), true);
print_r($data);

//path to database file
$database_path = $_SERVER["DOCUMENT_ROOT"] . "\WoIstMein.accdb";
//check file exist before we proceed
if (!file_exists($database_path)) {
    die("Access database file not found !");
}

//create a new PDO object
$database = new PDO("odbc:DRIVER={Microsoft Access Driver (*.mdb, *.accdb)}; DBQ=$database_path;");

try{    
$sql = 'INSERT INTO Gegenstaende (Koordinate_X, Koordinate_Y, Kategorie, Bild) VALUES (:koord_x,:koord_y,:kategorie,:bild);';
$statement = $database->prepare($sql);
$result = $statement->execute(array('koord_x' => $data["Koordinate_X"],'koord_y' => $data["Koordinate_Y"],'kategorie' => $data["Kategorie"], 'bild' => $data["Bild"]));
$database = null;
}catch(PDOException $e){
    echo $e->getMessage();
}

?>

EDIT

Thanks to H.B. I got the answer. I checked the network info and saw my app was sending two requests. Because of the headers tag I submitted in the fetch() command. So fetch first did an preflight to check the options and then commited the actual post command. So my solution was that I removed the "headers" from fetch.

about 4 years ago · Santiago Trujillo
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