Retrieving and displaying JSON data from URL - javascript

I am trying to retrieve and display information about current weather from a JSON object using javascript and a URL request:
http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805'
the data from the URL looks like this:
{
"data": {
"current_condition": [
{
"cloudcover": "75",
"humidity": "88",
"observation_time": "03:30 PM",
"precipMM": "2.7",
"pressure": "1008",
"temp_C": "12",
"temp_F": "54",
"visibility": "8",
"weatherCode": "302",
"weatherDesc": [
{
"value": "Moderate rain"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0018_cloudy_with_heavy_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "140",
"windspeedKmph": "17",
"windspeedMiles": "11"
}
],
"request": [
{
"query": "DE3",
"type": "Postcode"
}
],
"weather": [
{
"date": "2012-05-09",
"precipMM": "11.8",
"tempMaxC": "13",
"tempMaxF": "56",
"tempMinC": "12",
"tempMinF": "53",
"weatherCode": "266",
"weatherDesc": [
{
"value": "Light drizzle"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0017_cloudy_with_light_rain.png"
}
],
"winddir16Point": "SE",
"winddirDegree": "141",
"winddirection": "SE",
"windspeedKmph": "12",
"windspeedMiles": "7"
},
{
"date": "2012-05-10",
"precipMM": "11.1",
"tempMaxC": "18",
"tempMaxF": "64",
"tempMinC": "6",
"tempMinF": "43",
"weatherCode": "353",
"weatherDesc": [
{
"value": "Light rain shower"
}
],
"weatherIconUrl": [
{
"value": "http://www.worldweatheronline.com/images/wsymbols01_png_64/wsymbol_0009_light_rain_showers.png"
}
],
"winddir16Point": "SSW",
"winddirDegree": "209",
"winddirection": "SSW",
"windspeedKmph": "30",
"windspeedMiles": "19"
}
]
}
}
I have tried a couple of scripts to try and get the data and take bits out to display in a div. The first one looks like this:
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805"
dataType: 'json',
success: function(data) {
jQuery.each(data, function() {
alert("HELLO");
alert("Current Cloud Cover = " + this.data.current_condition.cloudcover);
alert("Current Humidity = " + this.data.current_condition.humidity);
});
}
});
the second one looks like this:
var postcode = document.getElementById("address").value;
function getWeather(userName, count) {
$.getJSON(
'http://free.worldweatheronline.com/feed/weather.ashx?q' + postcode + '&format=json&num_of_days=2&key=ec9c2dc5ba201904120805',
{},
showWeather,
//'jsonp'
);
}
function showWeather(day) {
var str = '<ul>';
str += '<h2>Tweets from ' + postcode + '</h2>';
var i = 0;
$.each(day, function(index, value) {
if (i == count) return;
var dt = new Date(value.date);
str += '<p>';
str += value.temp_C; //gets "text" from JSON
str += '</p>';
str += '';
str += '';
i++;
});
}
I want to get the weather information from the JSON URL and display some of the information in a div, can anybody explain how to do this is these two scripts dont work.

$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805",
dataType: 'jsonp', // You need to use 'jsonp' here because it is cross domain request
success: function(data) {
$.each(data, function(index, value) {
alert(value.current_condition[0].cloudcover);
alert(value.current_condition[0].humidity);
alert(value.current_condition[0].weatherDesc[0].value);
alert(value.request[0].query);
alert(value.request[0].query);
$.each(value.weather, function(i, val) {
alert(val.precipMM);
alert(val.weatherDesc[0].value);
})
});
}
});
DEMO

There are a few problems... the following should work (modification of the first block of code).
$.ajax({
url: "http://free.worldweatheronline.com/feed/weather.ashx?q=de39ga&format=json&num_of_days=2&key=ec9c2dc5ba201904120805&callback=?",
dataType: 'jsonp',
success: function(data){
jQuery.each(data, function(){
alert(JSON.stringify(this));
alert("Current Cloud Cover = " + this.current_condition[0].cloudcover);
alert("Current Humidity = " + this.current_condition[0].humidity);
});
}
});
To recap:
You need to use JsonP to circumvent cross-site-scripting restrictions (do that by adding "&callback=?" to the AJAX URL.
The root of the JSON response is data, so you need to write data.data.
The current_condition property is an array-- have to add an indexer (ie, [0]) to access it.

Related

Create JSON object with same keys for API call

I'm trying to create a JSON object for an API call which has the following format:
....
"Key": "Value",
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "20",
"Width": "25",
"Height": "30"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "80"
}
},
"Package": {
"Dimensions": {
"UnitOfMeasurement": {
"Code": "IN",
"Description": "inches"
},
"Length": "15",
"Width": "24",
"Height": "27"
},
"PackageWeight": {
"UnitOfMeasurement": {
"Code": "Lbs",
"Description": "pounds"
},
"Weight": "50"
}
},
"Key": "Value",
....
I should add as many "Package" objects as needed. However, I've tried doing this in many different ways but every time that I parse the variable to be used the first objects get overwritten and I end up with only the last object.
This is what I'm trying at the moment, still with no luck:
var lineItems = '{';
for (var i=0;i<inputObject.packages.length;i++) {
lineItems += '"Package": {"PackagingType": {"Code": "02","Description": "Rate"},"Dimensions": {"UnitOfMeasurement": {"Code": "IN","Description": "inches"},"Length": ' + inputObject.packages[i][0].toString() + ',"Width": ' + inputObject.packages[i][1].toString() + ',"Height": ' + inputObject.packages[i][2].toString() + '},"PackageWeight": {"UnitOfMeasurement": {"Code": "Lbs","Description": "pounds"},"Weight": ' + inputObject.packages[i][3].toString() + '}}';
if (i !== inputObject.packages.length-1) {
lineItems += ',';
}
}
lineItems += '}';
lineItems = JSON.parse(lineItems);
How about numbering your packages, ie:
for (var i=0;i<inputObject.packages.length;i++) {
lineItems+='"Package" + i : { ... }'
}
edit: to get required result (as an array - because it's not JSON), here's an example:
var a=[];
var b={"package": {"c":100,"d":200,"e":300}}
var c={"package": {"c":800,"d":700,"e":600}}
a.push(b);
a.push(c);
console.log(a);

how to chnge html header innertext according to javascript variable

if the value comes 9 or greater than 9 it should show good , if value between 6 - 9 bad and below 6 poor . how to change the header inner text dynamically according to the variable value- "turbidity". sample data - 9.00
<script>
FusionCharts.ready(function () {
LoadChart();
});
function LoadChart() {
$.ajax({
url: 'https://url', // local address
type: 'GET',
crossDomain: true,
success: function (data) {
console.log('xhr success')
//if (data.success) {
console.log("success");
var turbidity = data;
if (turbidity >= 9.0) {
$('#headerValue').text("Good");
}
if (turbidity < 9.0 && turbidity > 6.0) {
$('#headerValue').text("Normal");
}
if (turbidity < 6.0) {
$('#headerValue').text("Poor");
}
var phfusioncharts = new FusionCharts({
type: 'angulargauge',
renderAt: 'ph-container',
width: '450',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Turbidity",
"lowerLimit": "0",
"upperLimit": "12",
"showValue": "1",
"valueBelowPivot": "1",
"theme": "fint"
},
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "4",
"code": "#6baa01"
}, {
"minValue": "4",
"maxValue": "8",
"code": "#f8bd19"
}, {
"minValue": "8",
"maxValue": "12",
"code": "#e44a00"
}]
},
"dials": {
"dial": [{
"value": turbidity
}]
}
}
});
phfusioncharts.render();
//}
}
});
}
</script>
<td><h3 align="center">Water Quality : Good</h3> </td>
Write the html as this by giving id to status
<td><h3 align="center">Water Quality : <span id="status">Good</span></h3> </td>
Now when you'll get the result just use js to change the text
//Suppose you got data in var named data
if(data >=9 )
{
document.getElementById("status").innerText="Good"
}
else if(data >=6 && data <9 )
{
document.getElementById("status").innerText="Bad"
}
else
{
document.getElementById("status").innerText="Poor"
}

Weird issue where jQuery AJAX success data only parses last JSON node

So I have the following jQuery code:
function updateOrderSummary(orderID) {
var returnString = orderID;
$.ajax({
url: "library/getOrderSummary.php",
type: "POST",
data: ({returnString:returnString}),
success: function(data){
console.log(data);
}
});
}
When I run this script, the console shows the following JSON:
{"orderDetails":{"orderItem":{"itemName":"351","itemQuantity":"2","itemID":"5-5331fbfd5e0e7","costPerPlay":"2"},"orderItem":{"itemName":"Demo","itemQuantity":"1","itemID":"5-54067191b71e8","costPerPlay":"1"},"orderItem":{"itemName":"314","itemQuantity":"1","itemID":"5-5331f5b41f9f4","costPerPlay":"1"}}}
Formatted, it looks like this (for your convenience):
{
"orderDetails": {
"orderItem": {
"itemName": "351",
"itemQuantity": "2",
"itemID": "5-5331fbfd5e0e7",
"costPerPlay": "2"
},
"orderItem": {
"itemName": "Demo",
"itemQuantity": "1",
"itemID": "5-54067191b71e8",
"costPerPlay": "1"
},
"orderItem": {
"itemName": "314",
"itemQuantity": "1",
"itemID": "5-5331f5b41f9f4",
"costPerPlay": "1"
}
}
}
The JSON validates when I run it through JSONLint (jsonlint.com), but I can't seem to parse through the data when I add the dataType: "json" into my script. (ie:)
function updateOrderSummary(orderID) {
var returnString = orderID;
$.ajax({
url: "library/getOrderSummary.php",
type: "POST",
data: ({returnString:returnString}),
dataType: "json",
success: function(data) {
console.log(data);
}
});
}
When I do this, my console only seems to show the last "node" of the JSON string that gets returned. And I can't seem to parse through it the way I normally do.
Ultimately, all I want to be able to do is get the number of "orderItems" that exist in the return string (in this case, 3), and display the "itemName" for each. So something like this:
for (var a = 0; a < numNodes; a++) {
returnString += data.orderDetails.orderItem[a].itemName;
}
Alas, nothing I do seems to let me drill down into the JSON.
Any thoughts?
change your json structure to below format. instead of object with same key(orderItem), group it as an array.
{
"orderDetails": {
"orderItem": [{
"itemName": "351",
"itemQuantity": "2",
"itemID": "5-5331fbfd5e0e7",
"costPerPlay": "2"
},
{
"itemName": "Demo",
"itemQuantity": "1",
"itemID": "5-54067191b71e8",
"costPerPlay": "1"
},
{
"itemName": "314",
"itemQuantity": "1",
"itemID": "5-5331f5b41f9f4",
"costPerPlay": "1"
}
]
}
}
The problem is your structure is set up as object with 3 identical keys.
Since object keys can't be identical the whole property gets over written ...leaving only the last one
Structure needs to be changed to array of objects
SOmething like this would be more appropriate
"orderDetails": [
{ "itemName": "351","itemQuantity": "2" ....},
{ "itemName": "567","itemQuantity": "34" ....}
]

Google Chart is not rendering and display " Data table is not defined " instead

I'm not why my Google chart is not rendering and instead, it display
I also notice I got this error message on my console.
Uncaught TypeError: Cannot read property 'danger' of undefined
Then, I checked my JSON file, danger is there. which danger is it referring to ?
JS
'use strict';
define(['jquery'], function($) {
$(function() {
var danger = $('#pc-danger');
var warning = $('#pc-warning');
var success = $('#pc-success');
var danger_list = $('#pc-danger-list');
var warning_list = $('#pc-warning-list');
var success_list = $('#pc-success-list');
var basePath = "/BIM/resources/js/reports/student/section-exercise/";
$.ajax({
url: basePath + "data.json",
type: "GET",
dataType : "json",
success: function( objects ) {
function updateInfo(x) {
danger.html(objects[x].danger);
warning.html(objects[x].warning);
success.html(objects[x].success);
danger_list.html(objects[x].danger_list);
warning_list.html(objects[x].warning_list);
success_list.html(objects[x].success_list);
}
// Load the Visualization API and the piechart package.
google.load("visualization", "1", {packages:["corechart"]});
google.setOnLoadCallback(drawChart());
function drawChart() {
var options = {
width: 160,
height: 160,
chartArea: {
left: 10,
top: 20,
width: "100%",
height: "100%"
},
colors: ['#F46E4E', '#F9C262' , '#ADB55E',],
legend: 'none',
enableInteractivity: false,
pieSliceText: 'none',
};
var data = {};
var chart = {};
for (var object in objects) {
var total = objects[object].danger + objects[object].warning + objects[object].success ;
data[object] = google.visualization.arrayToDataTable([
['Piechart' , 'Number of Skills'],
['danger' , ( objects[object].danger/total ) * 100 ],
['warning' , ( objects[object].warning/total ) * 100 ],
['success' , ( objects[object].success/total ) * 100 ],
]);
object = object.toLowerCase();
// piechart object
var $el = $('#sa-piechart-' + object );
// button
var button = $('.sa-report-btn-'+ object );
// append
var $el = $('#sa-piechart-' + object ).length ? $('#sa-piechart-' + object ) : $('<div id="sa-piechart-' + object +'"></div>').appendTo($('#sa-piechart-'+ object ));
chart[object] = new google.visualization.PieChart($el[0]);
chart[object].draw(data[object]);
// attach click handler to the button
button.click(function() {
updateInfo(object);
chart[object].draw(data[object]);
});
}
}
},
error: function( xhr, status, errorThrown ) {
alert( "Sorry, there was a problem!" );
console.log( "Error: " + errorThrown );
console.log( "Status: " + status );
console.dir( xhr );
},
});
});
});
JSON
{
"A": {
"report_type": "chapter test",
"section_num": "2",
"assignment": "algebra 1",
"date": "2/10/2015",
"correct_num": "15",
"avg_score": "89",
"danger": "5",
"danger_list": "5,10,15,19,23",
"warning": "8",
"warning_list": "3,7,11,13,14,16,21,22",
"success": "12",
"success_list": "1,2,4,6,8,9,12,17,18,20,24,25"
},
"B": {
"report_type": "section exercise",
"section_num": "2.2",
"assignment": "algebra 1",
"date": "2/09/2015",
"correct_num": "11",
"avg_score": "44",
"danger": "12",
"danger_list": "11,12,13,14,15,16,17,18,19,20,3,4",
"warning": "2",
"warning_list": "1,2",
"success": "11",
"success_list": "21,21,23,24,25,5,6,7,8,9,10"
},
"C": {
"report_type": "test",
"section_num": "1",
"assignment": "algebra 1",
"date": "1/10/2015",
"correct_num": "15",
"avg_score": "75",
"danger": "0",
"danger_list": "",
"warning": "10",
"warning_list": "1,2,3,4,5,6,7,8,9,10",
"success": "15",
"success_list": "11,12,13,14,15,16,17,18,19,20,21,22,23,24,25"
},
"D": {
"report_type": "practice test",
"section_num": "1",
"assignment": "algebra 1",
"date": "1/09/2015",
"correct_num": "15",
"avg_score": "79",
"danger": "5",
"danger_list": "1,2,3,4,5",
"warning": "0",
"warning_list": "",
"success": "20",
"success_list": "6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25"
}
}
Any help / hints / suggestions will mean a lot to me.
Thank-you !
You are pushing DataTable to data[object] which are A,B,C.. and after that you conver it to lowerCase by this line:-
object = object.toLowerCase();
so after that when you get that object it return null in this line:-
chart[object].draw(data[object]);
so you just need to remove this line:-
object = object.toLowerCase();
here is demo( i just use one div for demo purpose)
Demo
hope this will help you.

jQuery autocomplete display worng search item

how can jQuery autocomplete match input word with list from json object. When I start typing some word in input field jQuery displays wrong results. I think autocomplete show only list from json object. Dont know what is the problem on this autocoplete. So if you coud give me advice to solve this on some other way.
When I select some value in serachbox results this code will append all results to other inputs as value. This is my code:
jQuery
$( document ).ready(
$("#get_search").autocomplete({
source: function( request, response ) {
$.ajax({
url: "/organizations/",
type: "GET",
dataType: "json",
data: {term: request.term},
contentType: "application/json; charset=utf-8",
success: function(data) {
response($.map(data, function(item) {
console.log(item.name);
return {
org_name: item.name,
oib: item.oib,
address: item.address,
city: item.city,
postal_code: item.postal_code
};
}));
}
});
},
minLength: 2,
scroll: true,
select: function(event, ui) {
//this.value = ui.item.org_name;
//console.log(ui.item.org_name+' '+ui.item.oib+' '+ui.item.address);
$('#get_search').val(ui.item.org_name);
$('#oib').val(ui.item.oib);
$('#address').val(ui.item.address);
$('#city').val(ui.item.city);
$('#postal_code').val(ui.item.postal_code);
return false;
}
}).data("autocomplete")._renderItem = function(ul, item) {
return $("<li>").data("item.autocomplete", item).append("<a><strong>" + item.org_name + "</strong><br>" + item.oib + " - " + item.address + " - " + item.city + "</a>").appendTo(ul);
});
json object
[
{
"id": "8",
"oib": "213214214",
"name": "asdasdd",
"address": "asdad",
"city": "asdasd",
"postal_code": "asdads"
},
{
"id": "8",
"oib": "213214214",
"name": "asdasdd",
"address": "asdad",
"city": "asdasd",
"postal_code": "asdads"
},
{
"id": "8",
"oib": "213214214",
"name": "asdasdd",
"address": "asdad",
"city": "asdasd",
"postal_code": "asdads"
},
{
"id": "8",
"oib": "213214214",
"name": "asdasdd",
"address": "asdad",
"city": "asdasd",
"postal_code": "asdads"
},
]
html
<input class="form-control ui-autocomplete-input" id="get_search" name="form1-name" type="text" autocomplete="off">

Categories