Looping through JSON with jQuery - javascript

Sorry, I'm sure there's a duplicate of this but I'm really new to jQuery. I have the following JSON string...
{
"totalNumEntries":2,
"pageType":"CampaignPage",
"totalBudget":{
"period":{
"value":"DAILY"
},
"amount":{
"comparableValueType":"Money",
"microAmount":0
},
"deliveryMethod":null
},
"entries":[
{
"id":733413,
"name":"Interplanetary Cruise #1345659006301",
"status":null,
"servingStatus":null,
"startDate":null,
"endDate":null,
"budget":null,
"biddingStrategy":null,
"conversionOptimizerEligibility":null,
"campaignStats":{
"startDate":null,
"endDate":null,
"network":{
"value":"ALL"
},
"clicks":null,
"impressions":null,
"cost":null,
"averagePosition":null,
"averageCpc":null,
"averageCpm":null,
"ctr":null,
"conversions":null,
"viewThroughConversions":null,
"statsType":"CampaignStats"
},
"adServingOptimizationStatus":null,
"frequencyCap":{
"impressions":0,
"timeUnit":null,
"level":null
},
"settings":null,
"networkSetting":null,
"forwardCompatibilityMap":null
},
{
"id":733414,
"name":"Interplanetary Cruise banner #1345659006387",
"status":null,
"servingStatus":null,
"startDate":null,
"endDate":null,
"budget":null,
"biddingStrategy":null,
"conversionOptimizerEligibility":null,
"campaignStats":{
"startDate":null,
"endDate":null,
"network":{
"value":"ALL"
},
"clicks":null,
"impressions":null,
"cost":null,
"averagePosition":null,
"averageCpc":null,
"averageCpm":null,
"ctr":null,
"conversions":null,
"viewThroughConversions":null,
"statsType":"CampaignStats"
},
"adServingOptimizationStatus":null,
"frequencyCap":{
"impressions":0,
"timeUnit":null,
"level":null
},
"settings":null,
"networkSetting":null,
"forwardCompatibilityMap":null
}
]
}
This is returned from /google/getCampaigns in my application. I'm looping through it with the following code, but the page stays blank...
<script>
$(document).ready(function() {
$.getJSON('google/getCampaigns', function(data) {
$.each(data.entries, function(index) {
$('span').append(index.name);
});
});
});
</script>
Loading...
<span />
Can anyone see what I'm doing wrong?
Thanks,
David

The each statement should like this:
$.each(data.entries, function(index,element) {
$('span').append(element.name);
});
or another approach would be
$.each(data.entries, function(index) {
$('span').append(data.entries[index].name);
});
Hope this will fix your problem.

what is the need of passing anything else not even index this will help you for sure
$.each(data.entries, function() {
$('span').append(this.name);
});

Related

How to fetch data from an API which stream real time data

I want to use this API here,
https://developer.sportradar.com/docs/read/basketball/NCAA_Mens_Basketball_v7#tournament-summary-seeded-tournaments-only
This endpoint retrieves detailed, real-time information on every game event. I am trying to implement this in node JS. How can I do this? This API redirect to different URL whenever we hit it. Is there any way to do parse data from this? It returns response like this,
{
"heartbeat":{
"interval":5000
}
}
{
"payload":{
"game":{
"id":"0db78438-9663-470f-b3ae-1f9106298e47",
"status":"inprogress",
"coverage":"full",
"scheduled":"2021-02-27T17:00:00+00:00",
"home":{
"name":"Hoosiers",
"market":"Indiana",
"id":"c3f0a8ce-af67-497f-a750-3b859376b20a",
"points":57,
"rank":0,
"bonus":true,
"remaining_timeouts":2
},
"away":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"points":73,
"rank":3,
"remaining_timeouts":1
}
},
"event":{
"id":"a2b43bd2-1b79-4823-b76c-21a09eb1adea",
"event_type":"rebound",
"sequence":1614445806980,
"clock":"18:32",
"clock_decimal":"18:32",
"updated":"2021-10-26T16:29:17Z",
"created":"2021-02-27T17:10:06Z",
"description":"Hunter Dickinson defensive rebound",
"home_points":57,
"away_points":73,
"attribution":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"team_basket":"right"
},
"location":{
"coord_x":102,
"coord_y":236,
"action_area":"backcourt"
},
"possession":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277"
},
"period":{
"id":"1f18ca8c-6a96-43f7-b68c-4d1b333e059c",
"number":1,
"sequence":1,
"type":"half"
},
"on_court":{
"home":{
"name":"Hoosiers",
"market":"Indiana",
"id":"c3f0a8ce-af67-497f-a750-3b859376b20a",
"players":[
{
"full_name":"Aljami Durham",
"jersey_number":"1",
"id":"6897db83-b25f-4c54-832a-0ff0c3cb86ff"
},
{
"full_name":"Rob Phinisee",
"jersey_number":"10",
"id":"481ffe40-392b-4a1b-89ec-0d9453495639"
},
{
"full_name":"Jerome Hunter",
"jersey_number":"21",
"id":"681d2cc6-24b9-4f38-8564-8c0b210a9535"
},
{
"full_name":"Trayce Jackson-Davis",
"jersey_number":"23",
"id":"c468bdc9-4778-496a-985e-7911dc6a1ff2"
},
{
"full_name":"Race Thompson",
"jersey_number":"25",
"id":"ed56bced-c614-4eeb-85ee-812edb594752"
}
]
},
"away":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277",
"players":[
{
"full_name":"Hunter Dickinson",
"jersey_number":"1",
"id":"1d0c6b20-76b7-4a82-ae1d-20b78136525b"
},
{
"full_name":"Isaiah Livers",
"jersey_number":"2",
"id":"34736ed7-c86a-472c-8c1c-683002de6487"
},
{
"full_name":"Mike Smith",
"jersey_number":"12",
"id":"92f6b357-f6cb-40a5-8893-329425fff5ba"
},
{
"full_name":"Franz Wagner",
"jersey_number":"21",
"id":"ec3df621-2a9d-483c-9064-11b44d8841a9"
},
{
"full_name":"Eli Brooks",
"jersey_number":"55",
"id":"8869c334-f08c-4ed9-931c-9d9c657cb7bc"
}
]
}
},
"statistics":[
{
"type":"rebound",
"rebound_type":"defensive",
"team":{
"name":"Wolverines",
"market":"Michigan",
"id":"bdc2561d-f603-4fab-a262-f1d2af462277"
},
"player":{
"full_name":"Hunter Dickinson",
"jersey_number":"1",
"id":"1d0c6b20-76b7-4a82-ae1d-20b78136525b"
}
}
]
}
},
"locale":"en",
"metadata":{
"league":"NCAAM",
"match":"sd:match:0db78438-9663-470f-b3ae-1f9106298e47",
"status":"inprogress",
"team":"sd:team:bdc2561d-f603-4fab-a262-f1d2af462277",
"players":"sd:player:6897db83-b25f-4c54-832a-0ff0c3cb86ff,sd:player:481ffe40-392b-4a1b-89ec-0d9453495639,sd:player:681d2cc6-24b9-4f38-8564-8c0b210a9535,sd:player:c468bdc9-4778-496a-985e-7911dc6a1ff2,sd:player:ed56bced-c614-4eeb-85ee-812edb594752,sd:player:1d0c6b20-76b7-4a82-ae1d-20b78136525b,sd:player:34736ed7-c86a-472c-8c1c-683002de6487,sd:player:92f6b357-f6cb-40a5-8893-329425fff5ba,sd:player:ec3df621-2a9d-483c-9064-11b44d8841a9,sd:player:8869c334-f08c-4ed9-931c-9d9c657cb7bc",
"event_type":"rebound",
"event_category":"shot",
"locale":"en",
"operation":"update",
"version":"v7"
}
}
{
"heartbeat":{
"interval":5000
}
}
you can use interval to get the data from API and then passing the data to websocket server
Use eventsource if this event is triggered by your API.
https://developer.mozilla.org/en-US/docs/Web/API/EventSource
Otherwise websocket is much better, than setInterval.

Change the way a collection is sorted through the client

I have a collection that is shown on a page :
Template.body.helpers({
chansonsFutures(){
return Chansons.find({
"playedStatus":false
},{
sort : { score:-1 }
});
},
});
And I would like the user to be able to change the way the collection is sorted. In the example it is sorted by score, but how would I go about sorted by something else?
I have a select in place :
<select id="ordre">
<option value="shuffle">Aléatoire</option>
<option value="vote">Vote</option>
<option value="lastAdded">Dernier Ajout</option>
</select>
But if I put an if condition in Template.body.helpers, meteor tells my application has errors and is waiting for file changes. If I put the condition in Template.body.events and link it to the change of my select, it also gives me errors.
How should I proceed?
edit : to answer #Justinas, here is how I put the condition in code.
My first try was straight in the helper :
Template.body.helpers({
if(document.getElementById("ordre").value == "lastAdded"){
chansonsFutures(){
return Chansons.find({
"playedStatus":false
},{
sort : { lastAdded:-1 }
});
},
};
else if (other value for the select) {
other stuff happens
};
});
And the other way was like this :
Template.body.events({
'change #ordre'(event){
event.preventDefault();
chansonsFutures(){
return Chansons.find({
"playedStatus":false
},{
sort : { document.getElementById("ordre").value:-1 }
});
},
},
});
Here it is what you need to add in your js fiile :
By defalult it will sot by 'score' and on changing select value it will change accordingly.
Template.body.onCreated(function() {
this.sortBy = new ReactiveVar('score');
})
Template.body.helpers({
chansonsFutures : function(){
var sortParam = Template.instance().sortBy.get();
return Chansons.find({
"playedStatus":false
},{
sort : { sortParam:-1 }
});
},
});
Template.body.events({
'change #ordre':function (event,templateInstance) {
var sortSelected = $('#ordre option:selelcted').val();
templateInstance.sortBy.set(sortSelected)
}
})

Subscribing the collection (Meteor)

I have some specific problem.
I use MeteorJS and installed yogiben:admin. I tried to build some schema, but I have an error after updating something.
I want to add that I have subpages in page, maybe that's the problem?
That's what I get after adding items to my invoice:
http://s7.postimg.org/l0q52l27v/error.png
As I can see in the picture, the problem is with some modifier and with "After.Update.sum". I use function that use "sum".
In my "server/collections/invoices_item.js"
I have:
InvoicesItem.after.update(function(userId, doc, fieldNames, modifier, options) {
var sum = 0; InvoicesItem.find({ invoiceId: doc.invoiceId }).map(function(item) { sum += item.amount; }); Invoices.update({ _id: doc.invoiceId }, { $set: { totalAmount: sum }});
});
Than I saw that problem could be with "totalAmount:sum". I use Chrome, so I tried "console.log()" to see if the page takes my collection.
And it doesn't.
I use Chrome, so I tried to see what the console will give me. I have something like this: http://s4.postimg.org/rusm4wx9p/fakturka.png
I did sth like that in my code on server side:
Meteor.publish("fakturka", function(invoiceId) {
return Invoices.find({_id:invoiceId,ownerId:this.userId}, {});
});
And did that on client side:
this.InvoicesNewInsertController = RouteController.extend({
template: "InvoicesNew",
yieldTemplates: {
'InvoicesNewInsert': { to: 'InvoicesNewSubcontent'}
},
onBeforeAction: function() {
/*BEFORE_FUNCTION*/
this.next();
},
action: function() {
if(this.isReady()) { this.render(); } else { this.render("InvoicesNew"); this.render("loading", { to: "InvoicesNewSubcontent" });}
/*ACTION_FUNCTION*/
},
isReady: function() {
var subs = [
Meteor.subscribe("invoices_item"),
Meteor.subscribe("invoiceeeee"),
Meteor.subscribe("customers"),
Meteor.subscribe("fakturka", this.params.invoiceId),
Meteor.subscribe("invoices_item_empty_faktura"),
Meteor.subscribe("invoices_itemss_faktura", this.params.invoiceId)
];
var ready = true;
_.each(subs, function(sub) {
if(!sub.ready())
ready = false;
});
return ready;
},
data: function() {
return {
params: this.params || {},
invoices_item: InvoicesItem.find({}, {}),
invoiceeeee: Invoices.find({}, {}),
customers: Customers.find({}, {}),
fakturka: Invoices.findOne({_id:this.params.invoiceId}, {}),
invoices_item_empty_faktura: InvoicesItem.findOne({_id:null}, {}),
invoices_itemss_faktura: InvoicesItem.find({invoiceId:this.params.invoiceId}, {})
};
/*DATA_FUNCTION*/
},
onAfterAction: function() {
}
});
I'm sorry for so much code, but I really want to solve that problem and I want to give so much info as I could. Please, help me to solve my problem.
After removing that code from: both/collections/invoices.js
Schemas={};
Schemas.Invoicess = new SimpleSchema({
invoiceNumber:{
type:Number
},
date_issued:{
type:Date
},
date_due:{
type:Date
},
customerId:{
type:String
},
totalAmount:{
type:String
}
});
Invoices.attachSchema(Schemas.Invoicess);
"fakturka" is visible. After adding that code - "fakturka" in undefined.

Jquery Vegas Plugin overlay not working

I am using the plugin off of http://vegas.jaysalvat.com/documentation/slideshow/
The backgrounds are changing fine, but the overlay image is not working or rendering.
Here is my code I have in the head of the page:
<script>
$.vegas('slideshow', {
backgrounds:
[
{ src:'/../../images/backdrop.png' },
{ src:'/../../images/backdrop_yellow_trees.png' },
{ src:'/../../images/backdrop.png' }
]
})('overlay', {
src:'/../../assets/vegas/overlays/13.png'
});
</script>
Same problem here, but based on the #pawel reply over I came to this
$(function() {
$.vegas('slideshow', {
backgrounds:[
{ src:'images/pic1.jpg', fade:800 },
{ src:'images/pic2.jpg', fade:800 },
{ src:'images/pic3.jpg', fade:800 },
{ src:'images/pic4.jpg', fade:800 }
]
})('overlay', {
src:'vegas/overlays/15.png'
});
});
We probably made the same mistake, just copy paste from the documentation...

Angularjs and jquery html5Loader

In my app i try to create a preloader with jquery.html5loader like this :
$.html5Loader({
filesToLoad: 'load.json', // this could be a JSON or simply a javascript object
onBeforeLoad: function () {
$('body').append('<div id="load">Loading....</div>');
},
onComplete: function () {
$('#load').hide();
console.log('Complete Loaded');
},
onElementLoaded: function ( obj, elm) { },
onUpdate: function ( percentage ) {
// sleep(100000);
console.log(percentage);
$("#load").text(' '+percentage);
}
});
the script correctly work and i get Complete loaded log in console when all script loaded but i get another error on angular
Uncaught object angular.js:36
in my json file i load all script except jquery,angular.js,angular-route.js . i think the problem is because i have a this code in my html :
<html ng-app="myApp">
Probably you are doing something wrong. I've created this simple jsfiddle embedding angularjs in the page and everything seems to work.
$.html5Loader({
filesToLoad: {
files: [{
"type": "SCRIPT",
"source": "//cdnjs.cloudflare.com/ajax/libs/lodash.js/2.4.1/lodash.min.js",
"size": 4.096,
}]
},
onBeforeLoad: function() {
console.log('Before load');
$('body').append('<div id="load">Loading....</div>');
},
onComplete: function() {
$('#load').hide();
console.log('Complete Loaded');
},
onUpdate: function(percentage) {
// sleep(100000);
console.log(percentage);
$("#load").text(' ' + percentage);
}
});

Categories

Resources