I'm trying to visualize data from a JSON structure, retrieved via a REST service. I'm retrieving 3 JSON structure via a REST service, and they are dependent on each other. This means that I am nesting 3 Ajax calls. Each ajax call collects data dependent on the ajax call before. Example:
I retrieve all tasks for an department in a company. Based on data about the tasks i retrieve data about the person who requested it. Finally i retrieve data about who the task was assigned to. My code:
$( document ).ready(function() {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests?$filter=TaskStatusValue%20eq%20%27Not%20Started%27",
headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
success: function(data){
$.each(data.d.results, function(a, data) {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests("+data.RequesterId+")/CreatedBy",
headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
success: function(data2){
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests("+data.AssignedToId+")/AssignedTo",
headers: { 'accept': 'application/json;odata=verbose', 'content-type': 'application/json;odata=verbose'},
success: function(data3){
$(".inner").prepend('<p>'+data.Request +' <br>Submitted by: '+data2.d.Name+'<br>Assigned to: '+data3.d.Name+' | Due in: '+data.DueInDays+' day(s)</p>');
for(var i = 0; i < data3.d.Name.length; i++)
{
var AssignedTo = data3.d.Name[i];
for(var j = 0; j < AssignedTo.length; j++)
{
var version = AssignedTo[j];
}
}
console.log(version);
}
});
}
});
});
}
});
});
I'm getting all the relevant data by running an $.each loop to run through the structure. What i want to do is visualize on a graph or heatmap how many tasks have been assigned to person. So i'm trying to store the data in a javascript array, but without luck. I can see that my data is getting displayed just fine if i try to prepend it.
The problem is that by running the $.each function i get multiple instances of the same person. I would like to have (as an example) a chart which shows the persons who have assigned tasks and how many tasks.
Any suggestions on how to store and/or visualize it?
EDIT Callback structure:
function getAssignedTo(data3) {
$(".inner").prepend('<p>' + data.Request + ' <br>Submitted by: ' + data2.d.Name + '<br>Assigned to: ' + data3.d.Name + ' | Due in: ' + data.DueInDays + ' day(s)</p>');
}
function getRequester(data2) {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests(" + data.AssignedToId + ")/AssignedTo",
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose'
},
success: function getAssignedTo(data3)
});
}
function iterateResults(a, data) {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests(" + data.RequesterId + ")/CreatedBy",
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose'
},
success: function getRequester(data2)
});
}
function getTasks(data) {
$.each(data.d.results, function iterateResults(a, data))
}
function getHelpData() {
$.ajax({
url: "http://helpdesk.site.com/IT/_vti_bin/ListData.svc/ITHelpdeskRequests?$filter=TaskStatusValue%20eq%20%27Not%20Started%27",
headers: {
'accept': 'application/json;odata=verbose',
'content-type': 'application/json;odata=verbose'
},
success: function getTasks(data)
});
}
Related
I am creating a simple app using Spotify REST API and JQuery where users can find an artist, and then it will show info about the artist, related artists, and most listened to songs on-page. I created 3 ajax calls which u can see below and everything works, but I think that it can be written in a better way (promises maybe?).
The first ajax call gets id from the server and create some DOM elements. The second two ajax calls need id to run and also create DOM elements. There is also a delete button that should delete DOM elements built from the data of each ajax call.
Is it possible to have it nested using the best practice or this is the only way possible?
artistForm.submit((e) => {
e.preventDefault();
let inputSearchQuery = artistInput.val();
let searchQuery = encodeURI(inputSearchQuery);
$.ajax({
url: `${baseUrl}search?q=${searchQuery}&type=artist`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
}).done((resp) => {
const artistId = (resp.artists.items[0].id);
// working with data and appending them on DOM
$.ajax({
url: `${baseUrl}artists/${artistId}/top-tracks?country=CZ`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
}).done((resp) => {
// working with data and appending them on DOM
$.ajax({
url: `${baseUrl}artists/${artistId}/related-artists`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
}).done((resp) => {
// working with data and appending them on DOM
deleteArtist.click(() => {
// need to have acces to data from every ajax call.
})
});
});
});
});
Given your work case, you could consider the following method:
artistForm.submit(async (e) => {
e.preventDefault();
let inputSearchQuery = artistInput.val();
let searchQuery = encodeURI(inputSearchQuery);
let artist = await $.ajax({
url: `${baseUrl}search?q=${searchQuery}&type=artist`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
const artistId = artists.items[0].id;
let topTracks = await $.ajax({
url: `${baseUrl}artists/${artistId}/top-tracks?country=CZ`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
let relatedArtists = await $.ajax({
url: `${baseUrl}artists/${artistId}/related-artists`,
type: 'GET',
datatype: 'json',
headers: {
'Authorization': 'Bearer ' + accessToken
}
});
deleteArtist.click(() => {
// need to have access to data from every ajax call.
});
});
This is assuming you are using jQuery 3.0 or higher. If not you can find a nice wrapper function here.
If you want to learn more about promises and async await I recommend the following video's: JavaScript Promises In 10 Minutes - by Web Dev Simplified
and The Async Await Episode I Promised - by Fireship.
If you have questions about the code above, please add a comment.
I hope this helps you continue with your project (and that you've learn something along the way 👍).
I have a function which is as follows:
//Calling the Function with one Parameter
responses(baseURL);
//Function Definition
function responses(baseURL) {
$.ajax({
url: baseURL,
type: "get",
cache: false,
headers: {
'Content-Type': 'application/json'
},
success: function (data) {
console.log(data.features.length);
for (var i = 0; i < data.features.length; i++) {
if (taxArrayT1.indexOf(data.features[i].properties.taxon_id) == -1) {
taxArrayT1.push(data.features[i].properties.taxon_id);
}
}
console.log("In the Invertebrate Animals Section 1");
console.log(taxArrayT1.length);
}
})
}
Now I tend to repeat myself because when I hit different services with the same function. I know how to pass the base URL as a parameter. Also there is an array like in this example, taxArrayT1. This array changes every time a different input is used, like taxArrayT2. It would be great if you have suggestions on how to accomplish. It would be of great help.
If I understand correctly what you are trying to do then you can just add the array as a second parameter. Like this:
function responses(baseURL, taxArray) {
$.ajax({
url: baseURL,
type: "get",
cache: false,
headers: {
'Content-Type': 'application/json'
},
success: function (data) {
console.log(data.features.length);
for (var i = 0; i < data.features.length; i++) {
if (taxArray.indexOf(data.features[i].properties.taxon_id) == -1) {
taxArray.push(data.features[i].properties.taxon_id);
}
}
console.log("In the Invertebrate Animals Section 1");
console.log(taxArray.length);
}
})
}
And the service calls will look like this:
responses(url1, taxArrayT1);
responses(url2, taxArrayT1);
I am working with the Spotify Web Playback SDK and an AJAX function fails whenever I put a variable under the data tag/section. However, when I put the contents of the variable under data, it works flawlessly. window.Thingy is equal to '{"uris": ["spotify:track:2xYlyywNgefLCRDG8hlxZq","spotify:track:3FCto7hnn1shUyZL42YgfO"]}'
With variable:
function play(device_id) {
ListPlaylistTracks(); //Gets output of JSON and saves it to window.Thingy
$.ajax({
url: "https://api.spotify.com/v1/me/player/play?device_id=" + device_id,
type: "PUT",
data: window.Thingy, //Variable that doesnt work.
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
success: function(data) {
window.dvcID = device_id;
window.PlayBack = true;
}
});
}
Without variable:
function play(device_id) {
ListPlaylistTracks();
$.ajax({
url: "https://api.spotify.com/v1/me/player/play?device_id=" + device_id,
type: "PUT",
data: '{"uris": ["spotify:track:2xYlyywNgefLCRDG8hlxZq","spotify:track:3FCto7hnn1shUyZL42YgfO"]}',
beforeSend: function(xhr){xhr.setRequestHeader('Authorization', 'Bearer ' + _token );},
success: function(data) {
window.dvcID = device_id;
window.PlayBack = true;
}
});
}
Direct comparison:
data: window.Thingy,
vs
data: '{"uris": ["spotify:track:2xYlyywNgefLCRDG8hlxZq","spotify:track:3FCto7hnn1shUyZL42YgfO"]}',
Any help is greatly appreciated, thanks!
I am using ajax to get JSON from an API, however I am having a problem, retrieving the data. The code for ajax function is fine as I am using it elsewhere. I believe that the issue is with the .done(function().
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
//dataType: 'json',
//method: 'GET',
//contentType: 'application/json'
data: {url: developmentURL},
method: 'POST'
})
.done(function(data) {
//var developments = [];
$.each(data, function() {
$.each(this, function(i, obj) {
console.log(i, obj.Name + ' = ' + obj.ItemKey);
//developments.push();
});
});
})
.fail(function() {
alert('Failed to fetch data')
});
This is the code I am using, which just logs loads of 0 "undefined=undefined". However I have the .done(function() working in a jsfiddle, with the JSON hard coded. So I'm not sure where the problem lies.
Here is the fiddle
The data is of string type. Parse the string into JSON before looping:
data = JSON.parse(data);
$.each(data, function() {
If you want to avoid using JSON.parse you can Set the dataType to just 'json' and you will automatically recieve a parsed json response:
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
dataType: 'json', //Uncomment this line
//method: 'GET',
//contentType: 'application/json'
data: {
url: developmentURL
},
method: 'POST'
})
Or you can also make use of jquery $.getJSON api.
I assume the data that you retrive is an array of Json according to your code.
You forgot add key and value in the $.each callback function to loop into each Json value.
$.ajax({
url: "http://127.0.0.1:4001/Barratt/getData.php",
//dataType: 'json',
//method: 'GET',
//contentType: 'application/json'
data: {url: developmentURL},
method: 'POST'
})
.done(function(data) {
//var developments = [];
$.each(data, function(key,value) {
$.each(value, function(subKey, subValue) {
console.log(subKey, subValue.Name + ' = ' + subValue.ItemKey);
//developments.push();
});
});
})
.fail(function() {
alert('Failed to fetch data')
});
All the examples I find online are of earlier versions of the Imgur API or non JS code all of which uses an API key which doesn't exist in the newer API. Instead you get a client_id and secret. Anyone have example code that shows how an image can be uploaded to Imgur through JavaScript (or jQuery) using version 3 of their API?
$.ajax({
url: 'https://api.imgur.com/3/image',
headers: {
'Authorization': 'Client-ID YOUR_CLIENT_ID'
},
type: 'POST',
data: {
'image': 'helloworld.jpg'
},
success: function() { console.log('cool'); }
});
Building on #vin's example here is one:
$(document).ready(function() {
$.ajax({
url: 'https://api.imgur.com/3/image',
headers: {
'Authorization': 'Client-ID a1b2c3d4e5'
},
type: 'POST',
data: {
'image': image
},
success: function(data, status) {
console.log("Data: " + data.data.link + "\nStatus: " status);
console.log(data.data.link)
}
});
});
This lets you save the url to the file.