How to load json data using AJAX call - javascript

I want to load JSON data into HTML file.
Problem is, it does not load json data and when I add error event then it gives me error alert for error object. Please guide me how I could resolve this issue. even, I could not find any specific alert to identiy the error. how to resolve this ? Is there any way to get actual error while working with jquery/ajax ?
Below is my html file which has jquery call to json data with html:
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
<script src="Scripts/jquery-1.7.1.min.js"></script>
<script src="Scripts/jquery-ui-1.8.20.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#btn382").click(function () {
/* set no cache */
$.ajaxSetup({ cache: false });
$.getJSON("car-sale.json", function (data) {
var html = [];
alert('result');
});
});
});
</script>
</head>
<body>
<input type="submit" id="btn382" />
</body>
</html>
JSON file is as follow:
[{
"Manufacturer": "Toyota",
"Sold": 1200,
"Month": "2012-11"
}, {
"Manufacturer": "Ford",
"Sold": 1100,
"Month": "2012-11"
}, {
"Manufacturer": "BMW",
"Sold": 900,
"Month": "2012-11"
}, {
"Manufacturer": "Benz",
"Sold": 600,
"Month": "2012-11"
}, {
"Manufacturer": "GMC",
"Sold": 500,
"Month": "2012-11"
}, {
"Manufacturer": "HUMMER",
"Sold": 120,
"Month": "2012-11"
}]

in the page header you should define this
<script src="car-sale.json"></script>
i check this with a firefox and its working fine check this with firefox
$.getJSON('car-sale.json', function (data) {
$.each( data, function( key, val ) {
console.log(val.Manufacturer );
});
});

Related

How to generate a jstree using AJAX?

I have been having problems generating a JsTree using data from my server. I have tried different formats and appending an existing tree, no dice. The only thing that happens is that it the jstree div gets replaced by
<div id="jstree" class="jstree jstree-1 jstree-default jstree-leaf" role="tree" aria-multiselectable="true" tabindex="0" aria-activedescendant="j1_loading" aria-busy="false"><ul class="jstree-container-ul jstree-children" role="group"></ul></div>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>jsTree test</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/themes/default/style.min.css" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jstree/3.2.1/jstree.min.js"></script>
</head>
<body>
<div id="jstree">
</div>
<script>
$(function() {
$.ajax({
async : true,
type : "GET",
url : "/treeTest2",
dataType : "json",
success : function(json) {
// alert(JSON.stringify((json)));
createJSTrees(json);
},
error : function(xhr, ajaxOptions, thrownError) {
alert(xhr.status);
alert(thrownError);
}
});
});
function createJSTrees(jsonData) {
$("#jstree").jstree({
"json_data" : {
"data" : jsonData
},
"plugins" : [ "themes", "json_data", "ui" ]
}).bind("select_node.jstree", function (e, data) {
alert(e);
});
}
</script>
</body>
</html>
Heres what the alert(JSON.stringify((json))); returns
[
{
"a_attr": {
"id": 1
},
"text": "lvl1",
"icon": "snipplet",
"metadata": null,
"children": [
{
"a_attr": {
"id": 3
},
"text": "lvl2",
"icon": "snipplet",
"metadata": null,
"children": [
{
"a_attr": {
"id": 5
},
"text": "lvl3",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
},
{
"a_attr": {
"id": 4
},
"text": "lvl2",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
},
{
"a_attr": {
"id": 2
},
"text": "lvl1",
"icon": "snipplet",
"metadata": null,
"children": []
}
]
The metadata tag is needed for data that will be needed later. Everything will be otganised into folders and snipplets. And the id tag will be used in hyperlinks.
I believe id="jstree" conflicts with the global variable jstree.
Indeed, If you give an ID to an element, this element is directly available in JS, without doing anything :
myGreatDiv.innerHTML = "It works"
<div id="myGreatDiv"></div>
So, you include the JsTree library, which defines window.jstree.
Then, you create a div with id="jstree", which automatically overwrites window.jstree.
Solution (I guess) : call your div something else, like
<div id="jstree_div">
Here's the solution.
function createJSTrees(jsonData) {
$("#kautkas").jstree({
'core' : {
'data' : jsonData
}
});
}

Script error when webbrowser loading html page

I'm trying to load local html page using webbrowser tool in Winforms but I got script error message and my page won't load, when I open that page using any web browser it opens with no problem at all! I tried some solutions as editing registry but no fix.
my html page has jscript code and this is the code in my page:
<html>
<head>
<script type="text/javascript"src="http://static.fusioncharts.com/code/latest/fusioncharts.js"></script>
<script type="text/javascript"src="http://static.fusioncharts.com/code/latest/themes/fusioncharts.theme.fint.js?cacheBust=56"></script>
<script type="text/javascript">
FusionCharts.ready(function () {
var csatGauge = new FusionCharts({
"type": "angulargauge",
"renderAt": "chart-container",
"width": "400",
"height": "250",
"dataFormat": "json",
"dataSource": {
"chart": {
"caption": "Customer Satisfaction Score",
"subcaption": "Last week",
"lowerLimit": "0",
"upperLimit": "100",
"theme": "fint"
},
"colorRange": {
"color": [
{
"minValue": "0",
"maxValue": "50",
"code": "#e44a00"
},
{
"minValue": "50",
"maxValue": "75",
"code": "#f8bd19"
},
{
"minValue": "75",
"maxValue": "100",
"code": "#6baa01"
}
]
},
"dials": {
"dial": [
{
"value": "67"
}
]
}
}
});
csatGauge.render();
});
</script>
</head>
<body>
<div id="chart-container">An angular guage will load here!</div>
</body>
</html>
I've managed to solve it by adding this code:
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge"/>
</head>
I'm still not sure if this is only thing needed or it worked with the change of the registry: solution

how to show pop up alert message without blocking the page to render and how to refresh chart in each 30 sec

i want to show pop up if value is less than 3 . i used alert function but when this alert event is fired page is not rendering. how to show popup without blocking the page to display , and how to refresh the chart every 30 sec.
<script>
FusionCharts.ready(function () {
LoadChart();
});
function LoadChart() {
$.ajax({
url: '#Url.Action("get", "air")',//remote api address
type: 'GET',
crossDomain: true,
success: function (data) {
if (data.success) {
var dust= data.sensorsdata.cl;
if (dust > 3)
alert("dust is high");
$("#lblDate").text(data.sensorsdata.CurrentTime);
$("#currenttime").show();
var dustchart= new FusionCharts({
type: 'angulargauge',
renderAt: 'ph-container',
width: '450',
height: '300',
dataFormat: 'json',
dataSource: {
"chart": {
"caption": "Chlorine ",
"lowerLimit": "0",
"upperLimit": "14",
"showValue": "1",
"valueBelowPivot": "1",
"theme": "fint"
},
"colorRange": {
"color": [{
"minValue": "0",
"maxValue": "5",
"code": "#6baa01"
}, {
"minValue": "5",
"maxValue": "10",
"code": "#f8bd19"
}, {
"minValue": "10",
"maxValue": "14",
"code": "#e44a00"
}]
},
"dials": {
"dial": [{
"value": dust
}]
}
}
});
dustchart.render();
}
}
});
}
</script>
<td><div id="dust-container" style="float:left;"></div></td>
Javascript modals will always block page. You need to implement your own popup code or use library for example bootstrap modal
http://getbootstrap.com/javascript/
Another way you can think of if you are doing just simple notifications is using something called toastr (or growl) - there are libs for this also.
For updating fussioncharts look at this example
http://www.fusioncharts.com/dev/using-with-javascript-libraries/jquery/updating-chart-properties-using-jquery.html#changing-the-data-for-an-existing-chart

AngularJS rendering from deeply nested jsonp

I am new to JSON and also AngularJS. I'm trying to access data elements in a deeply nested remote json file. I can manage to render the whole JSON results in my view. However, I can't seem to target the elements that are in an array deep inside the JSON. It's from Yahoo Currency.
This is my controller and view that renders the entire JSON file:
controller
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
$scope.data = data;
});
});
view
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="app.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="row in data">
{{ data }}
</li>
</ul>
</body>
</html>
I tried writing the controller like this:
var app = angular.module('app', []);
app.controller('DataCtrl', function ($scope, $http) {
$http.jsonp('https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20json%20where%20url%3D%22http%3A%2F%2Ffinance.yahoo.com%2Fwebservice%2Fv1%2Fsymbols%2Fallcurrencies%2Fquote%3Fformat%3Djson%22&format=jsonp&callback=JSON_CALLBACK').success(function (data) {
var pair = { name };
// $scope.data = data;
if(data) {
if (data.results) {
pair.name = data.results.list.resources[0].resource.fields.name;
}
}
});
});
But that doesn't work. Here is the JSON (partial) .. I'm trying to access the "name", "price", and "utctimestamp" fields for each resource:
{
"query": {
"count": 1,
"created": "2015-11-07T05:42:03Z",
"lang": "en-US",
"diagnostics": {
"publiclyCallable": "true",
"url": {
"execution-start-time": "0",
"execution-stop-time": "23",
"execution-time": "23",
"content": "http://finance.yahoo.com/webservice/v1/symbols/allcurrencies/quote?format=json"
},
"user-time": "25",
"service-time": "23",
"build-version": "0.2.311"
},
"results": {
"list": {
"meta": {
"type": "resource-list",
"start": "0",
"count": "173"
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/KRW",
"price": "1152.994995",
"symbol": "KRW=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "SILVER 1 OZ 999 NY",
"price": "0.068046",
"symbol": "XAG=X",
"ts": "1446850711",
"type": "currency",
"utctime": "2015-11-06T22:58:31+0000",
"volume": "100"
}
}
},
{
"resource": {
"classname": "Quote",
"fields": {
"name": "USD/VND",
"price": "22364.000000",
"symbol": "VND=X",
"ts": "1446874620",
"type": "currency",
"utctime": "2015-11-07T05:37:00+0000",
"volume": "0"
}
}
},
...
For what it's worth, jsonp seems to return some kind of xml-looking stuff when I append the callback=JSON_CALLBACK to the url, like this:
JSON_CALLBACK({"query":{"count":"1","created":"2015-11-07T16:08:29Z","lang":"en-US"},"results":["<list><meta><type>resource-list</type><start>0</start><count>173</count></meta><resources><resource><classname>Quote</classname><fields><name>USD/KRW</name><price>1152.994995</price><symbol>KRW=X</symbol><ts>1446900900</ts><type>currency</type><utctime>2015-11-07T12:55:00+0000</utctime><volume>0</volume></fields></resource></resources><resources><resource><classname>Quote</classname><fields><name>SILVER 1 OZ 999 NY</name><price>0.068046</price><symbol>XAG=X</symbol><ts>1446850711</ts><type>currency</type><utctime>2015-11-06T22:58:31+0000</utctime><volume>100</volume></fields></resource></resources><resources><resource>
...
Is there a problem with how I'm using JSONp? I'm getting the data set rendered to my view (above) but it's all in the funky xml syntax. How to go about grabbing the 3 values I need from that to an array and rendering in a <ul>??
You can use your original controller, you only had problems in the view. It would work if you substitute it by this one:
<!doctype html>
<html ng-app="app" >
<head>
<meta charset="utf-8">
<title>LIVE</title>
<!-- <link rel="stylesheet" href="style.css"> -->
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.js"></script>
<script src="script.js"></script>
</head>
<body ng-controller="DataCtrl">
<h1>Live from JSON feed</h1>
<ul>
<li ng-repeat="res in data.query.results.list.resources">
{{ res.resource.fields.name }}: {{ res.resource.fields.price }}, {{ res.resource.fields.utctime }}
</li>
</ul>
</body>
</html>
Here is the Plunker using your JSON example: http://plnkr.co/edit/wzF5t9dTZt49n5eq9N1L?p=preview

gantt chart using fusion charts. The chart doesn't get rendered a <div> element is created, with Chart type not supported as text

I wanted to create a gantt chart using fusion charts. The chart doesn't get rendered a element is created, with Chart type not supported as text. Using the fusion chart debugger I get an Error that p.init is not a function in fusioncharts.js
This is the code for the gantt chart.
enter code here
<html xmlns="http://www.w3.org/1999/html">
<head>
<title>Weekly Project Status Reports</title>
<script type="text/javascript" src="fusioncharts/fusioncharts.js"></script>
<script type="text/javascript" src="fusioncharts/fusioncharts.gantt.js"></script>
<script type="text/javascript" src="fusioncharts/fusioncharts.widgets.js"></script>
<script type="text/javascript" src="fusioncharts/themes/fusioncharts.theme.fint.js"></script>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script type="text/javascript">
FusionCharts['debugger'].outputTo(function (id, sender,
eventName, eventArgs) {
console.log(id + ': '+eventName + ' from ' + sender+','+eventArgs);
});
FusionCharts['debugger'].outputFormat('verbose');
FusionCharts['debugger'].enable(true);
</script>
<script type="text/javascript">
FusionCharts.ready(function(){
var weeklyStatusChart = new FusionCharts({
"type": "gantt",
"renderAt": "chartContainer",
"width": "1000",
"height": "500",
"dataFormat": "json",
"dataSource": {
"chart": {
"dateformat": "mm/dd/yyyy",
"caption": "Project Gantt",
"subcaption": "From 1st Feb 2007 - 31st Aug 2007"
},
"categories": [
{
"category": [
{
"start": "02/01/2007",
"end": "03/01/2007",
"label": "Feb"
},
{
"start": "03/01/2007",
"end": "04/01/2007",
"label": "Mar"
}
]
}
],
"processes": {
"fontsize": "12",
"isbold": "1",
"align": "right",
"process": [
{
"label": "Identify Customers"
},
{
"label": "Survey 50 Customers"
}
]
},
"tasks": {
"task": [
{
"start": "02/04/2007",
"end": "02/10/2007"
},
{
"start": "02/08/2007",
"end": "02/19/2007"
}
]
}
}
})
weeklyStatusChart.render();
});
</script>
</head>
<body>
<div id="chartContainer">--- Weekly Project Status</div>
</body>
</html>
The explicit loading of "fusioncharts.gantt.js" is not required, it will be automatically loaded by "fusioncharts.widgets.js".
If explicit loading is required, try loading "fusioncharts.widgets.js" followed by "fusioncharts.gantt.js"

Categories