How to get this data with AJAX from JSON? - json

I was using this code below to get the title/artist data from an old-station (https://stream.mydnic.be/status-json.xsl) with ajax:
(function worker() {
$.ajax({
url: host + '/status-json.xsl',
success: function(data) {
artist = data.icestats.source.artist;
title = artist + ' - ' + data.icestats.source.title;
document.title = title;
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 3000);
}
});
Now I changed the station and the new one use another JSON file that looks a little different:
"id": "station_name",
"songs":[
{
"title": "Water Silence",
"artist": "Solar Fields",
"album": "Fahrenheit Project Part Five",
"albumart": "",
"date": "1569618168"
},
The problem is that now, I get 'undefined' on Title and artist with the first Ajax Code.
So, I would like to ask if someone knows what I need to change on the first ajax code to work with the new JSON file and get the title/artist data correctly.
I really appreciate your help.

You are trying to get an attribute from an object when it is a list of objects, what you have to do is iterate the array or get the result by index.
Like this:
(function worker() {
$.ajax({
url: host + '/status-json.xsl',
success: function(data) {
//In this example you getting element by index
artist = data.songs[0].artist;
title = data.songs[0].title;
},
complete: function() {
// Schedule the next request when the current one's complete
setTimeout(worker, 3000);
}
});

Related

How to utilize a value from the response of one .AJAX function in another as a parameter to insert into the POST request

I'm trying to use a value received from the response in one ajax function as a parameter in another ajax function call in an html file.
I'm sorry if this is very basic, but I'm very new at this.
I've tried to call the value the same as I do in the body of the HTML and many other attempts.
1 - Here is the initial call (working):
$.ajax({
"url":api_base+"/endpoint_01",
"type":"GET",
"contentType":"application/json",
"success":function(data){
var data = data[0];
$('#dash_value').html(data.value);
}
});
2 - Here is how I access this in html (:
<div class="highlighted-text" id="dash_value"></div>
3 - I don't know how to utilize this later in the file:
function function_02(){
$.ajax({
"url":api_base+"endpoint_02?value=" + dash_value,
"type":"POST",
"beforeSend":function(){
$('#button_01').prop('disabled', true);
},
"dataType":"text",
"success":function(data){
swal(data, {
icon : "success",
buttons: false,
timer: 3000
});
},
"complete":function(){
$('#button_01').prop('disabled', false);
}
});
}
the POST should be sent like this:
https://endpoint02?value=dash_value
but I'm getting everything except that. Please help.
Try declaring a variable outside the scope of the Ajax method so code outside the method can access it later then assign the variable to the returned data inside the ajax scope:
var outerScopeData = "";
$.ajax({
"url":api_base+"/endpoint_01",
"type":"GET",
"contentType":"application/json",
"success":function(data){
var data = data[0];
// add this here:
outerScopeData = data.value;
$('#dash_value').html(data.value);
}
});
You need to define the dash_value before you make the second ajax call.
function function_02(){
const dash_value = $("dash_value").data()
$.ajax({
"url":api_base+"endpoint_02?value=" + dash_value,
"type":"POST",
"beforeSend":function(){
$('#button_01').prop('disabled', true);
},
"dataType":"text",
"success":function(data){
swal(data, {
icon : "success",
buttons: false,
timer: 3000
});
},
"complete":function(){
$('#button_01').prop('disabled', false);
}
});
}

Full Calendar feed with JSON ( Getting data from a restfull webservice )

i have this situation.
I need to use fullCalendar 3.8 to show some reservations.
I have the back end that give me the data in JSON format ( i have about 10 fields ).
In front-end i have a JSP that inlcude fullcalendar, moment and jquery. I need to populate my FullCalendar.
Example the Json that i have is in this form:
[
{
"idReservation": 21,
"idUser": 2,
"idSale": 1,
"timeStart": 1513839600000,
"timeEnd": 1513850400000
},
{
"idReservation": 22,
"idUser": 1,
"idSale": 1,
"timeStart": 1513854000000,
"timeEnd": 1513857600000
} ]
Someone can tell me where can i start to study, make test in the way to feed my calendar with this data ?
i have try to read a lot of articles but cause i am not a Front-End developer i am loosing around :)
The Javascript code that i created is this one:
$(document).ready(function() {
var value=2;
returnReservationsCalendar(value);
});
function returnReservationsCalendar(value){
var serviceEndpoint =
'http://localhost:8080/sale/'+value+'/reservations';
$.ajax({
type : 'GET',
url: serviceEndpoint,
dataType: 'json',
contentType : 'application/json',
success: function (result) {
$('#calendar').fullCalendar({
header: {
left: 'prev,next today',
center: 'title',
right: 'month,agendaWeek,agendaDay'
},
defaultDate: '2014-11-13',
editable: true,
eventLimit: true, // allow "more" link when too many events
events: function (start, end, timezone, callback) {
var events = [];
$.each(result, function (index) {
events.push({
"title": "Event " + index,
"start": result[index].timeStart.toISOString(),
"end": result[index].timeEnd.toISOString(),
});
});
callback(events);
}
});
},
error: function () { alert('Failed!'); }
});
}
At the JSP i have only this code:
<div id="calendar"></div>
The problem is that i have the json response from ajax but i dont understand where i am making the mistake about populating the calendar with the data from json.
You should be seeing errors in your browser's console similar to this (this is as per Google Chrome, others may vary slightly):
Uncaught TypeError: result[index].timeStart.toISOString is not a
function
Simply this is because timeStart is a string from your JSON, not a momentJS or Date object.
You need to pass it through the momentJS constructor before this will work:
events.push({
"title": "Event " + index,
"start": moment(result[index].timeStart).toISOString(),
"end": moment(result[index].timeEnd).toISOString(),
});
See http://jsfiddle.net/sbxpv25p/166/ for a working demo (using a static event list instead of ajax, but it demonstrates the part which is relevant to this answer.

fetching data from json file with ajax

I am building a sports site and need to acccess the json data that is accessible from http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json . On my page I am trying to get this data from an ajax. Here is my script below.
<div id="data"></div>
<script>
$.ajax({
url: 'http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json',
dataType: 'json',
success: function(data) {
var items = [];
$.each(data, function(key, value) {
$('#data').html(value);
});
},
});
</script>
When I do this i just get "261" on my page. I had assumed i would see all the values.
A lot of this data is nested and everything I read was just saying to do something like the script I have above. There are tons of different keys and values and I'll be trying to get select ones in the future. I have tried var variable = data.home.score; but that just got blank results..
Here is an example of some of the data when indented.
"home":{
"score":{
"1":0,
"2":10,
"3":7,
"4":0,
"5":0,
"T":17
},
Am I going about getting this data completely wrong? Can anyone help me get on the right path? Any insight or link's to answers that may help me would be much appreciated.
The JSON from the URL looks like the following, but I have shortened it for better readability.
{
"2012020500": {
"home": {
"score": {
"1": 0,
"2": 10,
"3": 7,
"4": 0,
"5": 0,
"T": 17
},
"abbr": "NE",
.....
.....
.....
},
"nextupdate": 261
}
The following loop reads key-value pairs from the received JSON and populates the value in '#data' . So for each element it replaces the old one. Since 261 is the last value, it is intact.
$.each(data, function(key, value) {
$('#data').html(value);
});
In order to print all the values in a node, it is required to dynamically create elements.
$.each(home, function(key, value) {
$('#data').append("<div>"+value+"<div>");
});
To get the scores, need to fetch the 'score' node and read the values like the following.
$.ajax({url: 'http://www.nfl.com/liveupdate/game-center/2012020500/2012020500_gtd.json',
dataType: 'json',
success: function(data) {
var score= data["2012020500"].home.score;
$.each(score, function(key, value) {
$('#data').append("<div>"+key+" - "+value+"<div>");
});
}
});

Getting Json formatted objects

Ok, so I have a big JSON file that has arrays and objects setup for controls for a google map project I am working on...looks like this:
{
"settings":
{
"DEFAULT_MAP_SETTING": "DEFAULT_MAP_SETTINGS",
"DEFAULT_MAP_RES": "county",
"DEFAULT_MAP_CAT": "popden"
},
"map_settings":
{
"DEFAULT_MAP_SETTINGS":
{
"map_options":
{
"center": [39.828175, -94.5795],
"mapTypeId": "TERRAIN",
"streetViewControl": false,
"scrollwheel": false,
"overviewMapControl": false,
"mapTypeControl": false,
"zoom": 4
},
"map_bounds":
{
"upper-left": [98.70, -127.50],
"lower-right": [48.85, -55.90]
},
}
}
}
My question is how do I go about getting this data in json format as it has to be in json format to load up options and what not in google maps. For instance I have
var myMapOptions = {
"zoom": 4,
"minZoom" : 4,
"scrollWheel" : false,
"center": initialLoc,
"mapTypeId": google.maps.MapTypeId.ROADMAP,
};
var theMap = new google.maps.Map(document.getElementById("map_canvas"), myMapOptions);
Which loads up the google map. But I cant figure out how to set myMapOptions with my big Json file. Every method that I know of returns the json data in strings and gets rid of the formatting. Like $.ajax in jQuery will go get the json for me but it strips it of its formatting.
Can anyone help me out?
jQuery $.ajax() will automatically transform you JSON "file" into a javascript object if your request come back with a JSON header.
However you can override this by using dataType of $.ajax:
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
alert(data);
}
});
The previous script will alert you JSON file like you want.
[Update]
You can try to use eval():
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
var options = eval(data);
}
});
In this case your data need to be executable by javascript.
[Update 2]
JsonP style, your json file need to looks like that:
var options = {
"zoom": 4, "minZoom" : 4,
"scrollWheel" : false,
"center": new google.maps.LatLng(39.828175, -94.5795),
"mapTypeId": google.maps.MapTypeId.ROADMAP
};
Notice the "var options ="
Your ajax request need to look like that:
$.ajax({
url: "test.html",
dataType: "text",
success: function(data){
alert(data);// will show your data as text
eval(data); this will execute your "JSON file"
//after eval you can now use options as a variable
alert(options);
}
});

How can I fetch json values and display in html

I have been killing myself over this for some time. I am looking to use the causes API to fetch some data from some of our causes we have active and display that via html.
I have created a facebook app and i'm trying to use jquery ajax. This is what I have:
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20xml%20where%20url%3D'http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.xml'&format=json&callback=cbfunc",
dataType: "json",
success: function(cbfunc) {
$(cbfunc).find('count').each(function(){
var total = $(this).find('total-raised').text();
$(this).html('<p>'+total+'</p>').appendTo('#listTotalDollor');
});
}
});
});
Problem is that I am not getting anything to display. Is this a crossdomain issue or is there something I missed.
Thanks!
Updated code:
<script type="text/javascript">
$(document).ready(function()
{
$.ajax({
url: "http://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.json%22&format=json",
dataType: "json",
success: function(data) {
$.each(data.query.results, function(i, key) {
var total = key['total_raised'];
$("#listTotalDollar").html('<span>' + total + '</span>');
});
}
});
});
One last question to ask:
If I wanted to format one of the returning values as currency.
In my updated code I get a return of 5000 I would like it to read $5,000. Is there a good tut you can point me to?
You are mixing DOM and JSON access in you cbfunc. Assuming, that you want that total-raised number for each of the elements returned by that query, you can simple request JSON (as you do) and iterate over it accordingly.
$.ajax({
// !wrapped only for readability!
url: "http://query.yahooapis.com/v1/public/yql?
q=select%20*%20from%20xml%20where%20url%3D'\
http%3A%2F%2Fapi.causes.com%2Fbeneficiaries%2F1239.xml'\
&format=json",
dataType: "json",
success: function(data) {
// `data` is actually a json structure (as requested)
// if you want to see it as a whole, just use
// console.log(data);
// now iterate over the json structure
// (see also: http://stackoverflow.com/q/1078118/89391)
// and set your target dom element as you like
// (this is just a dummy ...)
$.each(data.query.results, function(i, key) {
var total = key['total-raised'].content;
$("target").html('<p>' + total + '</p>');
});
}
});
Here's the code I used for debugging: https://gist.github.com/850148.
For reference, here's a sketch of the response:
Object
query: Object
count: 1
created: "2011-03-01T23:24:18Z"
lang: "en-US"
results: Object
beneficiary: Object
id: Object
name: "INTERNATIONAL FELLOWSHIP OF CHRISTIANS & JEWS"
recent-facebook-donors: "time1297716630facebook_id0nameRobert \
Alan Schoonoveramount200time1297372019facebook_id0nameCurtis En…"
total-causes: Object
total-donors: Object
total-members: Object
total-raised: Object
__proto__: Object
__proto__: Object
__proto__: Object
__proto__: Object