Edwin Martin Edwin Martin - 8 months ago 69
Ajax Question

Unable to display Json data using Promise and AJAX requests fetch API

Hi i am having issues retrieving the json data from my web services using a Promise and AJAX requests fetch API, the code fails on

return response.json();


The console shows this error


ajaxPromisesTask2.html:47 GET ***/hits.php?artist=dav 401 (Authorization Required)


but i have many working scripts that connect to the same webservice and retrieve the Json data, but this is my first Promise version using the inbuilt API. what am i doing wrong ?

link to Json webservice:
Json file


FYI, I have tried Json.parse(response);
and JSON.stringify(response);


<script type='text/javascript'>

function ajaxrequest()
{
var a = document.getElementById("artist").value;
fetch('/hits.php?artist=' + a).then(ajaxresponse).
then(showJSONResults).catch(ajaxerror);
}

function ajaxresponse(response)
{
return response.json();
}

function ajaxerror(code)
{
alert('error; ' + code);
}

function showJSONResults(jsonData)
{
var output = "<table style='width:100%'> <tr> <th>Title</th> <th>Artist</th> <th>Chart position</th> </tr>";
for(var i=0; i < jsonData.length; i++)
{
output = output + ' <tr> <td>' + jsonData[i].title + '</td><td>' + jsonData[i].artist + '</td><td>' + jsonData[i].chart + '</td></tr>';
}
output = output + "</table>";
document.getElementById("response").innerHTML = output;
}
</script>
</head>
<body>
<div id="info">
<input id="artist" /> <br/>
<input type="button" value="Search" onclick="ajaxrequest()" />
<div/>
<div id="response"><div/>

Answer Source

By default, fetch won't send or receive any cookies from the server, resulting in unauthenticated requests if the site relies on maintaining a user session (to send cookies, the credentials init option must be set).

Source: Using Fetch - Web APIs | MDN


You have to supply an object with a credentials property whose value is set to same-origin to submit the authorization cookie.

function ajaxrequest()
{ 
    var a = document.getElementById("artist").value;
    fetch('/hits.php?artist=' + a, { credentials: 'same-origin' })
        .then(ajaxresponse)
        .then(showJSONResults)
        .catch(ajaxerror);
}
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download