Skip to content

✈️ Promise based XMLHttpRequest function to get JSON data

License

Notifications You must be signed in to change notification settings

m-coding/promiseXHRgetJSON

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

5 Commits
 
 
 
 
 
 
 
 

Repository files navigation

promiseXHRgetJSON

Background

Created the getJSON function in a past project to get data when calling an API. Might be useful in the future or maybe someone else out there could use it too.

Usage

Example

var  params = {
    'userId': 1234,
};

getJSON('http://domain.com/something/api', {
    method: 'GET',
    apiquery: params,
})
.then(function (json) {
    console.log('Success!', json)
})
.catch(function (error) {
    console.log('API Failure: ' + error.status + ' ' + error.statusText);
});

Live Example

See index.html, demo using JSONPlaceholder:

var  params = {
    'albumId': 36,
    'id': 1751,
};
var result;

getJSON('https://jsonplaceholder.typicode.com/photos/', {
    method: 'GET',
    apiquery: params,
})
.then(function (json) {
    result = '<b>albumId:</b> ' + json[0].albumId;
    result += ' <b>id:</b> ' + json[0].id;
    result += '<h2>' + json[0].title + '</h2>';
    result += '<img src="' + json[0].thumbnailUrl + '" >';
    document.getElementById("content").innerHTML = result;
})
.catch(function (error) {
    result = 'API Failure: ' + error.status + ' ' + error.statusText;
    document.getElementById("content").innerHTML = result;
});

About

✈️ Promise based XMLHttpRequest function to get JSON data

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published