How to make an API call to show data? - javascript

I need to make an API call. The API consists of several arrays containing objects and the objects have 18 keys which I need to display.
How can I just display everything? I have tried doing fetch and ajax calls but none of them seem to work. What am I doing wrong here? Thanks beforehand.
async function events() {
return $.ajax("/api/address");
getEvents: function getEvents() {
return $.ajax("/api/address");
};
targetMarket: function targetMarket(id, events) {
return events.filter(function(event) {
return event.eventID === id;
});
};
eventsName: function eventsName(events, name) {
return events.filter(function(event) {
return events.event.eventID === events.eventID;
});
};
}

API calls can look a little intimidating starting off, keep at it!
Here's an example of getting simple data using an Ajax call to an API. This is in plain JavaScript, no libraries needed:
let cryptoData;
function ajaxGet(url) {
return new Promise(function(resolve, reject) {
let req = new XMLHttpRequest();
req.open('GET', url);
req.onload = function() {
if (req.status === 200) {
resolve(req.response);
cryptoData = JSON.parse(req.response); // the API response with the data is here (req.response). We use the JSON.parse() method to convert req.response string into a JSON object, since it originally comes in as a string.
showAjaxData();
} else {
reject(Error(req.statusText));
}
};
req.onerror = function(err) {
reject(Error("Looks like we've got an error..."));
};
req.send();
});
}
function showAjaxData() {
console.log(cryptoData[0]);
}
ajaxGet(`https://api.coinmarketcap.com/v1/ticker/bitcoin/`);
You can see the code in action at this JS Fiddle demo. Just remember to open the browser console to view the logged API data.
Feel free to check out this w3schools tutorial on Ajax calls.
Hope this helps :)

Related

Calling function from a function in javascript es6

I'm using es6 javascript with babel and trying to make an ajax call using xhr using two function but getting an error Uncaught TypeError: this.post is not a function
What is the correct syntax to make a call to a function from another function defined in the same class in es6 javascript?
Thanks for your answer this is my code
import alt from '../../alt';
import cookie from 'react-cookie';
class LoginActions {
constructor(){
this.generateActions(
'updatePassword',
'updateName',
'loginSuccess',
'loginFail',
'remember'
);
}
// Generic get request
post(url, data, callback) {
var xhr = new XMLHttpRequest();
xhr.open('POST', url, true);
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
if (xhr.status == 200) {
callback(null, xhr.responseText);
} else {
callback(xhr.statusText);
}
}
};
xhr.send(data);
}
// Get actual content
login(name, password, remember) {
var data = "name="+name+"&password="+password+"&remember="+remember;
this.post('api/login', data, function(err, data) {
if (!err) {
this.actions.loginSuccess(data.message);
} else {
this.actions.loginFail(JSON.parse(data.message));
}
}).bind(this);
}
}
export default alt.createActions(LoginActions);
Edit1: This is how I call login function / also passed data to xhr request above
handleSubmit(event){
event.preventDefault();
var name = this.state.name;
var password = this.state.password;
var remember = this.state.remember;
LoginActions.login(name, password, remember);
}
Your methods login() and post() are instance methods, not static methods. So you have to create an instance of your LoginActions object with new in order to properly call those methods on that object.
Or if you don't actually need an instance with instance data, then make all the methods static and refer to them as LoginActions.post() and LoginActions.login(), not using this.
Instead, you're trying to mix and match. You're calling LoginActions.login() which is a static type call and then inside of login(), you're trying to reference this which assumes an instance.
Give these things a try:
As #jfriend00 suggested, create an instance of LoginAction class and call login method on that:
var loginAction = new LoginActions();
loginAction.login(name, password, remember);
define generateActions method in LoginActions class.
this.post('api/login', data, function(err, data) {
if (!err) {
this.actions.loginSuccess(data.message);
} else {
this.actions.loginFail(JSON.parse(data.message));
}
}).bind(this);
Here, you seem to be trying to bind this to the callback. But actually you are binding this to the return value of post method. To bind this to the callback,
this.post('api/login', data, function(err, data) {
if (!err) {
this.actions.loginSuccess(data.message);
} else {
this.actions.loginFail(JSON.parse(data.message));
}
}.bind(this));
Notice function(){}.bind instead of the post(function(){}).bind

javascript asynchronous json http request in Model View structure using jQuery .when() .done()

I am trying to solve a problem where an asynchronous json request is made but the rest of the script runs before the request is completed which breaks the code. To complicate matters this is done in a MVC structure...
I make an asynchronous json request in the Controller which gets a json file and populates a model object with the data, basically:
model {
data: {}
}
controller {
init: function(){
function loadJSON(callback) {
var xobj = new XMLHttpRequest();
xobj.overrideMimeType("application/json");
xobj.open('GET', 'js/resumeInfo.json', true);
xobj.onreadystatechange = function() {
if (xobj.readyState == 4 && xobj.status == "200") {
// Required use of an anonymous callback as .open will
//NOT return a value but simply returns undefined in
//asynchronous mode
callback(xobj.responseText);
}
};
xobj.send(null);
};
loadJSON((response) => {
// Parse JSON string into object
this.JSONdata = JSON.parse(response);
// anything I want to do with model.data from here is all
// good, works fine...
model.dataBank = this.JSONdata;
view.init();
});
// ... but anything outside the above ^ scope will execute before the
//asynchronous request is completed and produce an 'undefined' error
//when trying to access model.data.
}
}
view {
// no good trying to access model.data here either because it executes
// before json http request has completed...
}
I have tried using jQuery ( which is passed into this module as a parameter ) .when and .done, but doesn't seem to work because it is not picking up the callback response.
Appreciate any ideas about how to access that call back response for $ .when .done?

Accessing JSON data from a url

I'm fairly new to web programming, so I'm sorry in advance if this is a dumb question. I've looked around and wasn't able to find anything very concrete on this so I figured I'd ask here.
I'm trying to make a script which reads a JSON file and returns some data. More specifically here's a link.
I want to search through and find where an world_id is equal to xxxx, and return the match_id. In another thread it one of the solutions was something similar to
var obj = JSON.parse(//JSON info here)
var a = obj.world_id
Can anyone point me in the right direction as to achieve this?
There are many reasons to add jQuery to a project. BUT. Please don't add jQuery just to get some json data. Javascript is perfectly capable of handling this one on its own, thank you:
// simple cross-browser ajax helper
var ajaxGet = function (url, callback) {
var callback = (typeof callback == 'function' ? callback : false), xhr = null;
try {
xhr = new XMLHttpRequest();
} catch (e) {
try {
xhr = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
xhr = new ActiveXObject("Microsoft.XMLHTTP");
}
}
if (!xhr)
return null;
xhr.open("GET", url,true);
xhr.onreadystatechange=function() {
if (xhr.readyState==4 && callback) {
callback(xhr.responseText)
}
}
xhr.send(null);
return xhr;
}
// example usage, grab the json data, loop it and log red_world_id to console
ajaxGet(
'https://api.guildwars2.com/v1/wvw/matches.json',
function (response) {
response = JSON.parse(response);
if (!response)
return;
var i, list = response.wvw_matches;
for (i in list) {
console.log(list[i].red_world_id); // outputs an id
}
});
Try it here: http://jsfiddle.net/7WrmL/
So basically, for your specific usage, instead of simply logging the ID to console, you can check each object's id properties against the desired matching id and, for example, return i for the index of the match (not sure I understand exactly what you're after there).
And keep in mind: use jQuery when you need it, not for everything and anything.
Documentation
XMLHttpRequest on MDN - https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest
XMLHttpRequest ON MSDN (IE) - http://msdn.microsoft.com/en-us/library/ie/ms535874%28v=vs.85%29.aspx
JSON on MDN - https://developer.mozilla.org/en-US/docs/JSON
for... on MDN - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for
An easy way of getting the JSON data is by using jQuery, like this:
<div id="reply"></div>
<script src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script>
$(function () {
$.getJSON(
"https://api.guildwars2.com/v1/wvw/matches.json",
function (data) {
$("#reply").html(JSON.stringify(data));
// or work with the data here, already in object format
});
});
</script>
See here: http://jsfiddle.net/mynetx/LwNKC/
Look at my code below. I used jquery to get content
var result;
$.get(
"https://api.guildwars2.com/v1/wvw/matches.json",
{},
function(data) {
var result = data;
}
);
var arr = JSON.parse(result);
var length = arr.length;
for (var i = 0; i < length; i++)
{
if(arr[i].red_world_id == 'xxx')
{
console.log('Got it');
}
if(arr[i].blue_world_id== 'xxx')
{
console.log('Got it');
}
if(arr[i].green_world_id== 'xxx')
{
console.log('Got it');
}
}
Look out for slip of the pen :).

Monkey patch XMLHTTPRequest.onreadystatechange

How would go about monkey patching the XMLHTTPRequest's onreadystatechange function. I'm trying to add a function that would be called when every ajax request made from a page come back.
I know this sounds like a terrible idea, but the use case is quite peculiar. I want to use a certain SDK with a console (jqconsole) but show status and results from ajax calls within the console without modifying the external SDK.
I've looked at this post which had great info, but nothing on monkey patching the callback which seem to exceed my JavaScript skills.
P.S Can't use jQuery since it only supports ajax calls made from jQuery not from XMLHTTPRequests directly which is the case here.
To monkey-patch XMLHttpRequests, you need to know how an AJAX request is generally constructed:
Constructor invocation
Preparation the request (setRequestHeader(), open())
Sending the request (.send).
General-purpose patch
(function(xhr) {
function banana(xhrInstance) { // Example
console.log('Monkey RS: ' + xhrInstance.readyState);
}
// Capture request before any network activity occurs:
var send = xhr.send;
xhr.send = function(data) {
var rsc = this.onreadystatechange;
if (rsc) {
// "onreadystatechange" exists. Monkey-patch it
this.onreadystatechange = function() {
banana(this);
return rsc.apply(this, arguments);
};
}
return send.apply(this, arguments);
};
})(XMLHttpRequest.prototype);
The previous assumed that onreadystatechange was assigned to the onreadystatechange handler. For simplicity, I didn't include the code for other events, such as onload. Also, I did not account for events added using addEventListener.
The previous patch runs for all requests. But what if you want to limit the patch to a specific request only? A request with a certain URL or async flag and a specific request body?
Conditional monkey-patch
Example: Intercepting all POST requests whose request body contains "TEST"
(function(xhr) {
function banana(xhrInstance) { // Example
console.log('Monkey RS: ' + xhrInstance.readyState);
}
//
var open = xhr.open;
xhr.open = function(method, url, async) {
// Test if method is POST
if (/^POST$/i.test(method)) {
var send = this.send;
this.send = function(data) {
// Test if request body contains "TEST"
if (typeof data === 'string' && data.indexOf('TEST') >= 0) {
var rsc = this.onreadystatechange;
if (rsc) {
// Apply monkey-patch
this.onreadystatechange = function() {
banana(this);
return rsc.apply(this, arguments);
};
}
}
return send.apply(this, arguments);
};
}
return open.apply(this, arguments);
};
})(XMLHttpRequest.prototype);
The main techniques used is the transparent rewrite using...
var original = xhr.method;
xhr.method = function(){
/*...*/;
return original.apply(this, arguments);
};
My examples are very basic, and can be extended to meet your exact wishes. That's up to you, however.
Assuming you can ignore IE...
//Totally untested code, typed at the SO <textarea>... but the concept *should* work, let me know if it doesn't.
var OldXMLRequest = XMLHttpRequest;
// Create a new instance
function XMLHttpRequest() {
var ajax = new OldXMLRequest();
// save old function
var f = ajax.onreadystatechange;
ajax.onreadystatechange = function() {
console.log("Whatever!");
f(); // Call the old function
}
return ajax;
}
you can learn from Ajax-hook written by chinese!
it is a advanced js to enable Monkey patch XMLHTTPRequest

Why does this function not return JSON string?

function addphoto()
{
var ajaxRequest = initAjax();
if (ajaxRequest == false)
{
return false;
}
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
alert(ajaxRequest.responseText);
return ajaxRequest.responseText;
}
}
// Capture form elements
var values = {
"category" : encodeURIComponent(document.addphoto.category.options[document.addphoto.category.selectedIndex].value),
"photo_title" : encodeURIComponent(document.addphoto.photo_title.value),
"photo_descrip" : encodeURIComponent(document.addphoto.photo_descrip.value)
}
var queryString = '?', i = 0;
for (var key in values)
{
if (i != 0)
{
queryString += '&'
}
queryString += key + '=' + values[key];
i++;
}
// Execute Ajax
ajaxRequest.open("POST", "ajaxcheckform.php" + queryString, true);
ajaxRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
ajaxRequest.setRequestHeader("Content-length", queryString.length);
ajaxRequest.setRequestHeader("Connection", "close");
ajaxRequest.send(null);
}
function ajaxCheckform(formname)
{
var response = addphoto(); // <--This is undefined and not sure why
var responseObj = JSON.parse(response);
if (responseObj.success == 1)
{
// Successful form!
alert(responseObj.success_text);
}
else
{
// Error!
alert(responseObj.error);
}
}
I'm sure I must be making some basic error somewhere, but I'm having trouble locating it. In this script, ajaxCheckform() is a function that executes one of several similar functions. Above, I included addphoto(), which is one of several functions I'll need that look like this.
On a side note, I'd love to know I can call upon a function dynamically. The addphoto() function will be only one such function being called up at that moment and I'm trying to find a way to pass formname as the function I need. I've searched Stackoverflow and Google. I've found nothing that works.
Note, I'm aware of jQuery, but I'm not there yet. I need this function to work first.
It is not addphoto() thats undefined but response is undefined. ajaxRequest is asynchronous and the addphoto() function will return before the request completes.
try this
function addphoto() {...
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
alert(ajaxRequest.responseText);
var responseObj = JSON.parse(ajaxRequest.responseText);
if (responseObj.success == 1) {
// Successful form!
alert(responseObj.success_text);
}
else {
// Error!
alert(responseObj.error);
}
}
}
....
}
function ajaxCheckform(formname) {
addphoto();
}
That's because response is set to the return of addphoto(), which is nothing. What you want to do is have ajaxCheckForm get called when the AJAX call is completed:
// Return Ajax result when the state changes later
ajaxRequest.onreadystatechange = function()
{
if(ajaxRequest.readyState == 4)
{
ajaxCheckform(ajaxRequest.responseText);
}
}
Then your ajaxCheckform will work with that data:
function ajaxCheckform(responseText)
{
var responseObj = JSON.parse(responseText);
if (responseObj.success == 1)
{
// Successful form!
alert(responseObj.success_text);
}
else
{
// Error!
alert(responseObj.error);
}
}
You can't return from an event handler (which onreadystatechange is).
You have to do the work inside that event handler.
addphoto() does not return anything (or rather, returns inconsistently) ... the onreadystatechange event's handler is returning the value, but there is no caller that will receive that json string.
I'd highly suggest that you abstract these details away with something like jquery ... just follow the docs for suggested usage and this code will be much simpler
You're sending a GET style parameter list to a POST method.
You need to send that string in the body of your HTTP request.
var response = addphoto(); // <--This is undefined and not sure why
The addphoto() function never has a return statement in it, so it returns undefined. And the ajaxRequest is asynchrous and wont return immediately.

Categories