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
},
Related
I am making a web site with Flask and I hope I can get all the product list from server, and append to options in select element.
This is my JS code
$('#addModalPopup').click(() => {
$.get('/getProductInfos', function(data){
for (var i = 0; i < data.length; i++){
$("#productInfo").append($("<option></option>")
.text(data[i].PRODUCT_INFOS));
}
})
})
And this is my python code
#purchasing_blueprint.route('/getProductInfos', methods=['GET'])
def get_products():
if request.method == 'GET':
time.sleep(2)
query_str = get_product_infos_query_string()
db = get_db()
cursor = db.cursor()
product_infos = cursor.execute(query_str)
colname = [ d[0] for d in product_infos.description ]
product_infos_list = [ dict(zip(colname, r)) for r in product_infos.fetchall()]
return jsonify(product_infos_list)
I put time.sleep() in server side to simulate the delay of request to DataBase
But I realized that the option will not be append if time.sleep() is exists in server side, but if I comment the sleep function, append goes will, is there any solution or reason ?
Cause if there are a big delay in the future, I think the scenario will be like this.
$('#addModalPopup').click(() => {
$.ajax({
type: 'GET',
url: '/getProductInfos',
contentType: "application/json; charset=utf-8",
traditional: true,
data: data,
success: function (result) {
for (var i = 0; i < result.length; i++){
$("#productInfo").append($("<option></option>")
.text(result[i].PRODUCT_INFOS));
}
}
});
});
use this code js
I can't tell why the sleep delay broke the request... But to simulate a delay on the response, you can do it on client-side with a setTimeout, after the response is received.
$('#addModalPopup').click(() => {
$.get('/getProductInfos', function(data){
setTimeout(function(){
for (var i = 0; i < data.length; i++){
$("#productInfo").append($("<option></option>")
.text(data[i].PRODUCT_INFOS));
}
},2000);
})
})
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]);
}
I'm not having any truly functional issues with this script but there's a slight bug here that I can't figure out.
The process: The user types in the input field #productInput. On each keystroke, the value they've typed thus far is sent to an endpoint via ajax, query results are returned and appended to an <option> dropdown for a <datalist>. This works but here's the issue:
If I type 'TES' I can see 7 products (TEST1, TEST2, TEST3, TEST4, TEST5, TEST6, TEST7). But when I complete the word and type 'TEST', it only shows one or two of those results, even though they all contain the word TEST. Is there an obvious issue here causing this bug that I'm missing?
$('#productInput').on('input', function() {
let _this = $(this);
let foundOption;
let optSelector = `option[value='${_this.val()}']`;
if (_this.val() === '') {
return;
} else if ($('#returnedProducts').find(optSelector).length) {
console.log("else");
} else {
const searchResult = $(this).val();
$.ajax({ url: '/autocomplete',
data: {
search_result:searchResult
},
"_token": "{{ csrf_token() }}",
type: "POST",
success: function (response) {
console.log(response);
$("#returnedProducts").empty();
var result = response.hits.hits;
//for each result in the object, append to option list
for (let i = 0; i < result.length; i++) {
$("#returnedProducts").append($("<option/>",
{
"srindex": i,
"data-attributes": JSON.stringify(result[i]._source.frame.group),
"data-covers":JSON.stringify(result[i]._source.covers[1]),
"value": result[i]._source.group_cover_color,
"html": result[i]._source.group_cover_color,
}
));
}
}
});
}
});
I want to gather some data from google Youtube by using its api. Here I trying to retrieve snippets (gapi.client.youtube.search.list request) in a loop for each keyword. And then for each snippet i trying to load its statistics with another request (gapi.client.youtube.videos.list). After all requests is completed i want to handle gathered data with ajax call;
The problem is that my ajax call starts to early, before stats requests done.
Here i used batch requests. By the way please explain how to grab data from their responses. They are with some random ids.
Hope i understand clear what i want. Please explain how can i chain my requests to make possible do something after all work is done.
Here is the code:
var stats = [];
var videoData;
var keys = ['car crash', 'cats', 'fail'];
function Init() {
gapi.client.setApiKey("myApiKey");
gapi.client.load("youtube", "v3", function () {
console.log("api is ready");
var keys = GetKeyWords();
RetrieveVideos(keys);
});
}
function RetrieveVideos(keys) {
var videoSearchBatch = gapi.client.newBatch();
for (n = 0; n < keys.length; n++)
{
var videoSearchRequest = MakeRequestForVideos(keys[n]);
videoSearchBatch.add(videoSearchRequest);
videoSearchRequest.then(function (response) {
GetStatistics(response);
});
}
//Here i want to make an ajax call and handle gathered data
videoSearchBatch.then(function (response) {
videoData = response.result.items;
$.ajax({
url: '/ajax/ajaxHandler.php',
type: 'post',
data: {'data': videoData, 'stats': stats},
success: function () {
console.log("OK!");
}
});
});
}
function MakeRequestForVideos(key) {
return gapi.client.youtube.search.list({
part: "snippet",
type: "video",
q: key,
maxResults: 50,
order: "viewCount",
publishedAfter: "2007-01-01T00:00:00Z"
});
}
function GetStatistics(response) {
var statsBatch = gapi.client.newBatch();
for (i = 0; i < response.result.items.length; i++)
{
var statsRequest = gapi.client.youtube.videos.list({
part: "statistics",
id: response.result.items[i].id.videoId
});
statsBatch.add(statsRequest);
statsRequest.then(function (response) {
stats.push(response.result.items[0].statistics);
});
}
statsBatch.then(function (response) {
console.log(response.result);
});
}
This is what i get in result
Promises are your friends. You can create an array of promises and use Promises.all() to return another promise that you can then work with.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/all
I have FullCalendar (1.6.4) working with a single JSON feed (a single user's calendar). Now, I want to enhance the functionality so the calendar will display multiple user calendars (the admin and their child account calendars). Until the calendar is called, I won't know how many user calendars will be called. So, I have a Ajax function call a PHP script that returns a JSON feed of all user ID's for the admin account.
$(document).ready(getUsers);
function getUsers() {
var data = $.ajax( {
url: '/s/calendar_userdata.php',
method: 'GET',
dataType: 'json',
success: function(userData) {
var user_count = userData.length;
var uid_array = [];
// Create the sources
for (var i = 0; i < user_count; i++)
{
var uid = userData[i].uid;
if(!uid_array[i]) uid_array[i] = [];
uid_array[i] = uid;
}
}
});
loadCal();
}
The Ajax call works. I get an array (uid_array) such as [7,47] back, as expected. I would like to use this array within my loadCal function as illustrated below, but I can't get it to persist after the getUsers function has concluded.
function loadCal() {
$('#calendar').fullCalendar({
eventSources: [
{
url: '/s/events.php',
type: 'GET',
data:
{
uid: uid_array
}
}
],
editable: true,
.........
I've tried:
1) Creating a global variable by initially defining uid_array outside of getUsers without the "var".
2) Setting "window.uid_array = uid_array;" within the getUsers function.
3) Adding "return uid_array;" at the end of the getUsers function.
4) Adding a closure at the end of the getUsers function. But, I don't grasp them well enough to believe I did it correctly.
I have 2 questions:
1) How do I make the array (uid_array) available outside of getUsers?
2) In what format does the array need to be so that fullCalendar will recognize and use it?
I've been stuck on this for a while. Thanks much.
I think if you change the location of loadCal function you can accomplish your objective:
function getUsers() {
var data = $.ajax( {
url: '/s/calendar_userdata.php',
method: 'GET',
dataType: 'json',
success: function(userData) {
var user_count = userData.length;
var uid_array = [];
// Create the sources
for (var i = 0; i < user_count; i++)
{
var uid = userData[i].uid;
if(!uid_array[i]) uid_array[i] = [];
uid_array[i] = uid;
}
//CALL loadCal FROM HERE
loadCal(uid_array);
}
});
}
Modify loadCal to accept array of uids:
function loadCal(uidArray) {
$('#calendar').fullCalendar({
eventSources: [
{
url: '/s/events.php',
type: 'GET',
data:
{
uid: uidArray
}
}
],
editable: true,
When you are making ajax call in getUsers it is not returned and loadCal is called. So you need to make sure that it is called only after ajax is returned that is in success callback.