By Mike Street
The default method for
GET. This allows you to pass in a URL and get the data from the other end. In the example below we are retrieving a JSON API. Using promises, the data is parsed and then made available for use.
The thing to note with asynchronous functions (in laymen's terms) is, although they fire when executed, they do not stop the rendering of the page. If part of your code requires the
fetch to be complete before firing, ensure it is triggered in the promise (the
Bonus: PHP example
This one took me a while to figure out, but capturing the POST variables from your
fetch function in a PHP script is not as obvious as it initially seems!
The key is using
php://input - which is a readable stream which contains the data as a JSON string (as sent with the fetch function). This can be decoded using the native PHP function.
<?php $input = json_decode(file_get_contents('php://input'), true); // $input['key'] would equal "value"
If you were to remove the
true from the end of the
json_decode, your data would be available as a PHP object instead, meaning you would access "value" using