1

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();
}
Sinan Samet
  • 6,432
  • 12
  • 50
  • 93
  • how do you defined the value of `name` that is being used in the body of the request – m_callens Jun 14 '17 at 15:46
  • "This returns to me Undefined index 'name'." — Where? Is that the PHP response (making this [a duplicate](https://stackoverflow.com/questions/4261133/php-notice-undefined-variable-notice-undefined-index-and-notice-undef))? Is that a JavaScript error? – Quentin Jun 14 '17 at 15:49
  • "I did this same this with jQuery.ajax() which did work" — What does the working code look like? It's hard to tell what you changed which broke it if we can't see that. – Quentin Jun 14 '17 at 15:50
  • Why are you setting the body to a JSON string without setting the Content-Type? – Quentin Jun 14 '17 at 15:51
  • I changed my question to contain the jQuery version. name is populated with a string from a text field. – Sinan Samet Jun 14 '17 at 15:52
  • I was just trying things I thought maybe it would work with stringify but that didn't either. – Sinan Samet Jun 14 '17 at 15:54
  • For what reason exactly are the downvotes? – Sinan Samet Jun 14 '17 at 16:03

1 Answers1

2

The working jQuery code

data: { name : name}

… so when you used jQuery you send WWW URL Form Encoded data (the default jQuery encoding).

body: JSON.stringify({name: name})

… but when you switched to fetch, you also converting the object to JSON.

JSON is not WWW URL Form Encoded!

You, presumably, haven't rewritten the PHP to expect JSON, and are probably trying to read from $_POST (which is empty, because PHP doesn't support JSON encoded requests by default).

You can construct a FormData object which will be encoded in a way that PHP will parse by default.

var body = new FormData;
body.append("name", name);
//...
body: body
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335