I'm trying the Fetch API for the first time and I'm trying to POST a variable to a PHP script. I did this same this with jQuery.ajax()
which did work.
var myRequest = new Request('invoeren.php', {method: 'POST', body: JSON.stringify({name: name})});
fetch(myRequest).then(function(response) {
console.log(response);
});
This returns to me Undefined index 'name'
.
What am I doing wrong?
The working jQuery code:
$.ajax({
url: "invoeren.php",
method: "POST",
data: { name : name}
}).done(function( msg ) {
console.log(msg);
}).fail(function( jqXHR, textStatus ) {
alert( "Naam is niet ingevoerd door een probleem: " + jqXHR );
});
The PHP Script:
try {
$dbh = new PDO('mysql:host=localhost;dbname=ajaxoef', $user, $pass);
$stmt = $dbh->prepare('INSERT INTO names(name) VALUES (:name)');
$stmt->bindParam(':name', $name);
$name = json_decode($_POST['name']);
$stmt->execute();
echo "Naam is ingevoerd.";
} catch (PDOException $e) {
print "Error!: " . $e->getMessage() . "<br/>";
die();
}