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.