We got a project for school were i need to create an mp3 album playlist using a premade PHP api using javascript or jquery only (Not allowed to use php).
I can enter the data using an ajax call.
I need to be able to enter more than one song with its url.
I managed to enter the data this way to the DB into a column named songs.:
[{"name":["song1","song2"],"url":["url1","url2"]}]
How do I loop through this using Javascript or jQuery and showing it as a list?
This is the ajax call I am using.
function getsongs(index, name, url){
$.ajax({
url: "api/playlist.php?type=songs&id=" + index,
method: 'GET',
data: {
"songs": [
{
"name": name,
"url": url
},
] },
success: function(response, playlist){
// Need to loop here?
},
error: function(xhr){
console.log('error')
console.log(xhr)
}
}); }
Thank you.
You can use "for" :
var arr = [{"name":["song1","song2"],"url":["url1","url2"]}];
var names = arr[0].name; // extract names from arr
var urls = arr[0].url; // extract urls from arr
for(var i=0; i< names.length && i < urls.length; i++){
console.log(names[i]);
console.log(urls[i]);
}
Related
I'm trying to find and use an english translation of a language JSON endpoint using the PokéAPI in an app I am developing. I need to utilise translations when submitting a call to one of the urls shown below. Unfortunately, the english language key is not always in the same order in the array response so I need a way of finding and checking for it so that the correct english translation is shown on the front-end.
Im trying to retrieve:
flavor_text_entries[X].language.en key in each search and retrieve the flavor_text_entries[X].flavor_text to show the description on the front-end.
API URL 1:
https://pokeapi.co/api/v2/pokemon-species/3/
API URL 2:
https://pokeapi.co/api/v2/pokemon-species/10/
Code:
var pokeBio = $("[data-poke-bio]").html();
function submit(){
var pokeID = $("[data-poke-id]").val();
var pokeSpecURL = "https://pokeapi.co/api/v2/pokemon-species/" + pokeID;
$.ajax({
type: "GET",
url: pokeSpecURL,
success: function(dataSpec){
ajaxSpecSuccess(dataSpec);
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
ajaxError();
}
});
}
function ajaxSpecSuccess(dataSpec){
var pokeMatchBio = dataSpec.flavor_text_entries[1].flavor_text;
var pokeBio = $("[data-poke-bio]").html(pokeMatchBio);
}
Snippet I need to manipulate:
var pokeMatchBio = dataSpec.flavor_text_entries[1].flavor_text;
Step 1, find the english entry
Step 2, display its flavor_text or a message if it wasn't found
let englishEntry = dataSpec.flavor_text_entries.find(entry => entry.language && entry.language.name && entry.language.name === 'en');
if (englishEntry) {
console.log(englishEntry.flavor_text);
} else {
console.log("English entry not found");
}
The Steam Web API has a function for getting information on a published Workshop file called GetPublishedFileDetails. It says I can make a request for multiple files, but I cannot figure out how to do this with Javascript. At the moment, I have to make multiple calls to the API, which seems unnecessary.
I've tried sending it an array, strings, everything I can think of.
for (let index = 0; index < arrayOfAddonIds.length; index++) {
$.ajax({
type: 'POST',
url: 'https://api.steampowered.com/ISteamRemoteStorage/GetPublishedFileDetails/v1/',
data: {
'itemcount': 1,
'publishedfileids[0]': parseInt(arrayOfAddonIds[index]),
},
dataType: 'json',
}).done((data) => {
console.log()
populateAddonList(addon_data);
}).fail((err) => {
console.log(err);
}).always((data) => {
var addon = data.response.publishedfiledetails["0"];
if (addon.result == 1) {
for (let i = 0; i < Object.keys(data).length; i++) {
var addonObject = {
"title": addon.title,
"id": addon.publishedfileid
}
addon_data.push(addonObject);
}
}
});
}
Is there a way I could achieve this in one call to the API?
This is also Electron app, maybe that opens up some possibilities.
I guess that you have to do an array like this:
data: {
'itemcount': 3, // Increase itemcount
'publishedfileids[0]': ID0,
'publishedfileids[1]': ID1,
'publishedfileids[2]': ID2, // Add items accordingly
},
i am trying to populate an asp.net dropdownlist returned as JSON from my webservice.
WebService
[WebMethod(EnableSession = true)]
public string GetActiveDepositAccountsForLoanAlert(string customerId)
{
var data = BusinessLayer.SMS.SmsSetup.GetActiveDepositAccountsForLoanAlert(customerId.ToLong());
var json = new JavaScriptSerializer().Serialize(data);
return json;
}
The webservice returns
[{"AccountNumber":"NS-0000092"},{"AccountNumber":"6MR-0000002"},{"AccountNumber":"1YFD-0000007"}]
I am calling the data from ajax call and populating it to my dropdownlist.
Ajax call
function GetActiveDepositAccounts(customerrId) {
var customerId = $('#CustomerIdHiddenField').val();
var data = { customerId: $('#CustomerIdHiddenField').val() };
var json_data = JSON.stringify(data);
$.ajax({
type: "POST",
url: "/WebMethods/Misc.asmx/GetActiveDepositAccountsForLoanAlert",
data: json_data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess,
failure: function (response) {
alert(response.d);
}
});
}
function OnSuccess(r) {
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i] + '</option>');
}
}
The data gets populated in json.In my dropdown i only want the accountnumber as
NS-0000092.I am getting the whole json in my dropdown.i have searched and seen lots of question with this Json parse thing in here.But couldnt get hold of this.It isnt that i didnt tried,I am newbie,so before marking this as duplicate,please for once have a look at the code.Thank you.
I can't shake the feeling that because your GetActiveDepositAccountsForLoanAlert is returning a string and not an object, r.d is being seen as a string. Try one of 2 things. Either:
Change your method signature to return data type and don't use the JavaScriptSerializer. or,
In your OnSuccess function, add var data = JSON.parse(r.d) and use that variable in your for loop.
Single Object Returned
If by "whole json", you mean you are getting a single {"AccountNumber":"6MR-0000002"} per option -- try outputting the value of the target AccountNumber object (e.g. r.d[i].AccountNumber or r.d[i]["AccountNumber"]).
Modified Function
var depositRadioList = $("[id*=DepositAccountDropDownList]");
depositRadioList.empty().append('<option selected="selected" value="0">Please select</option>');
for (var i = 0; i < r.d.length; i++) {
depositRadioList.append('<option>' + r.d[i].AccountNumber + '</option>');
}
Array of Objects Returned
If the result per option is an entire AccountNumber array of objects, you'll need to loop through your r object until you get to the list of Account Number objects.
Take a look at my Example JS Fiddle. There is probably a cleaner way to do this, but to present the principle, I've laid out nested loops to get you into the list of object values that you need for your <select></select>.
I'm using the JQuery $.each() method, but you can use the for loop. I recommend just using one or the other for consistency. If the data set is really large, for loops have better performance.
I use an AJAX request to get the data from the backend when user select an option from a dropdown menu.
$('#adSpace').change(function () {
var sel_opt = $(this).val();
alert(sel_opt);
var location = null;
var width = null;
var height = null;
$.ajax({
type: "GET",
dataType: 'json',
url: "advertisements-controller.php",
data: {
action: "getDimension",
location: sel_opt
},
success: function (response) {
location = response.banner_location;
alert(location);
},
error: function (xhr) {
alert("error");
}
});
});
Now i'm getting the data from backend in JSON format like below:
[{"banner_location":"category_group_sidebar","banner_width":250,"banner_height":225}]
I want to access the values of banner_location, banner_width, banner_height by assigning those to javascript variables but I'm failing to do it.
Any ideas?
Use this
location = response[0].banner_location;
Your response comes in the form of an array: [...]. That means you can access the first array item by using the index. Also if there are multiple objects you can iterate response with forEach or jQuery's each($(response).each).
response[0].banner_location
response is an array of json. In order to access the json you need to firsr access the index of the array which is done by array[indexNumber] then the key of the json.
In your case it will be response[0].banner_location
Archive.org json doc: http://archive.org/help/json.php
I am using this url: https://archive.org/metadata/AhmedAlajmiTheCompleteHolyQuran
The json format is displayed in this order
036.mp3
016.mp3
However the actual order on the details page is
001.mp3
002.mp3
The details page: https://archive.org/details/AhmedAlajmiTheCompleteHolyQuran
How can i get the uploaders sorted order that is displayed in the details page. How come the json is sorted in a different format. I can sort the urls based on the numbers, but the file name will not always be by numbers.
This is what i have so far. It just gets the mp3 urls. BUT THE ORDER IS WRONG!
var urlJ = "https://archive.org/metadata/AhmedAlajmiTheCompleteHolyQuran";
function functionName() {
var url = "https://archive.org/metadata/AhmedAlajmiTheCompleteHolyQuran";
var details = "https://archive.org/download/AhmedAlajmiTheCompleteHolyQuran";
function jsonpCallback(response) {
//after success some staff
var files = response.files;
for(var i=0; i < files.length; i++){
if(files[i].source == "original"){
console.log(details + "/" + files[i].name);
}
}
console.log(response.files[0]);
}
$.ajax({
url: url,
dataType: 'jsonp',
error: function(xhr, status, error) {
alert(error.message);
},
success: jsonpCallback
});
return false;
}
functionName();
There's no way to sort it with the API provided, however the metadata provides one piece of data you can use to sort it yourself.
mtime - Unix-style timestamp of file
Therefore, you can just sort it with JavaScript (put this right after you pull response.files):
var files = response.files;
for (var i = files.length - 1; i >= 0; i--)
if (typeof files[i].mtime === 'undefined')
files.splice(i, 1);
files.sort(function(a, b) {
return a.mtime - b.mtime;
});
Also, if you're only pulling the files, you can just request only the files with:
https://archive.org/metadata/AhmedAlajmiTheCompleteHolyQuran/files
When I run the code: