fetching data from json file with ajax - json

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>");
});
}
});

Related

How to get this data with AJAX from 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);
}
});

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.

How to have a custom value in JSON with JQueryi UI Autocomplete?

I'm using the JQuery UI autocomplete plugin (cached version) with JQuery-UI 1.11.1
Due to some server-side changes in the JSON I am using as source, I need to adapt my code.
Here is an example of my JSON:
[{
"name": "Varedo"
}, {
"name": "Varena"
}, {
"name": "Varenna"
}, {
"name": "Varese"
}]
produced by an URL with this style:
[url]/?name=vare
Since the GET variable is different from the default one ("term"), I already adapted my code for the custom request as suggested here:
$(function () {
var cache = {};
$("#searchTextField").autocomplete({
minLength: 3,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.getJSON("[url]", {
name: request.term
}, function (data, status, xhr) {
cache[term] = data;
response(data);
});
}
});
});
However I need to also adapt the code in order to use a custom JSON value (the default is "value" http://api.jqueryui.com/autocomplete/#option-source) which is in my case is "name" (as you can see from the JSON).
How can I do that?
At the moment this is what I get from the autocomplete:
So I guess I am somehow giving as response JS Objects and not strings.
Thanks in advance.
Currently you're saving the response as it is into your cache object, which is not valid format for jQuery UI autocomplete. You should convert the data into proper format digestable for autocomplete.
Either you should pass an array of strings, or an array of objects having label and value properties.
Since the response only contains name properties, you can convert it into an array of strings using jQuery map() method and save it in cache variable as follows:
$("#searchTextField").autocomplete({
minLength: 3,
source: function (request, response) {
var term = request.term;
if (term in cache) {
response(cache[term]);
return;
}
$.getJSON("[url]", {
name: request.term
}, function (data, status, xhr) {
cache[term] = $.map(data, function (obj) { // returns array of strings
return obj.name
});
// return the new array rather than original response
response(cache[term]);
});
}
});

Select2 ajax is correctly calling webservice, but then doing nothing after

I'm setting up a select2 with the following JavaScript
$j("#" + name).select2({
placeholder: "",
width:"300px",
minimumInputLength: 3,
ajax: {
url: "/MyService.asmx/ServiceMethod",
dataType: 'json',
data: function (term) {
return {
q: term // search term
};
},
results: function (data) {
alert('results');
return {results: data};
},
success: function() {
alert('success');
},
error: function () {
alert('error');
},
},
});
The method I'm calling is the following:
<WebMethod(enableSession:=True)>
<ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
Public Function ServiceMethod(q as String) As String
Dim temp As String = "[{'id':'35','text':'Drew'}]"
Return temp
End Function
I also have <ScriptService()> around the class. The enableSession is there because eventually I'm going to be running a lot of logic in the service that requires it, but for now I'm just trying to return a simple string with JSON.
I've put a breakpoint in the webservice, and I know it is being called. I know it is returning the JSON. I also know that the select2 expects "id" and "text" in the JSON return
My problem is the following: after I input 3 characters, the data function calls (I put an alert in it), the webservice breakpoint is hit, but none of the results, success, or error events fire afterwards. The select2 just spins and nothing ever happens. No javascript errors are entered in the console, and I'm at a loss about even where to look for information as to why the ajax isn't handling the returned value from the service.
Can anyone point me in the direction of at least where to look to see why this isn't working?
So I fixed this myself after getting a hint to look at the network log. The service was returning correctly, but it was returning XML, not JSON. I had to make 2 modifications and everything worked.
My working ajax:
ajax: {
url: "/MyService.asmx/ServiceMethod",
type: 'POST',
params: {
contentType: 'application/json; charset=utf-8'
},
dataType: 'json',
data: function (term, page) {
return JSON.stringify({ q: term, page_limit: 10 });
},
results: function (data) {
return {results: data};
},
},
The important changes were the type, putting the contentType in the params wrapper, and JSON.stringify-ing the data. I'm going to change what's passed and how its passed, but things are at least communicating now. Hope this helps anyone else who was looking for a similar solution.

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);
}
});