JavaScript: Using the fetch API

From The Travis van der Font Wiki
Jump to: navigation, search

Minimal GET Method Example

var url = 'http://travisfont.com/example/api/v1/test';

fetch(url)
.then((response) => response.json())
.then(function (data)
{
    console.log(data);

    // loops through each record row
    return data.map(function (record)
    {
        // ... actual code here
    });
})
.catch(function (error)
{
    console.log(JSON.stringify(error));
});
Note: This example does not support HTTPS or CORS functionality.

Full POST Method Example

fetch('/test/api/getData',
{
    method:  'POST',
    credentials: 'same-origin',
    //mode:   'cors',
    redirect: 'follow',
    headers: {
        'Accept':       'application/json',
        'Content-Type': 'application/json',
        //'Authorization': 'Basic '+btoa('username'+':'+'password123')
    },
    body: JSON.stringify(
    {
        date: date,
        lang: lang,
        sc:   sci_domain
    })
}).then(function (response)
{
    // okay status on the response
    if (response.status === 200)
    {
        return response.json();
    }

    if (response.status === 404)
    {
        return false;
    }

    // return whatever response as text
    return response.text();

}).then(function(response)
{
    /*console.log('--- response.length ---');
    console.log(response.length);*/

    // if the response has actual data
    if (response.length > 0)
    {

        // looping through the response
        for (row in response)
        {
            // allocating the response into data objects
            var data  = response[row];

            /*console.log('##############');
            console.log(data);*/

            var value = data.schedule;
            var name  = data.name;
            var begin = data.begin;
            var end   = data.end;
    
            // ...
        }
    }
    else
    {
        // ..
    }
}).catch(function (exception)
{
    //console.log('failed', exception);
    console.log('--- failed ---');
    console.log(exception);
});
To retrieve a fetch as above in PHP:
$input = file_get_contents('php://input');

if (!empty($input))
{
    $request = json_decode($input);

    var_dump($request)
}

Reference(s)