getJSON method does not work - javascript

Below is my code where getJSON method is not working
function loadJson() {
$(document).ready(function () {
alert("inside");
var chart;
var url = "values.json";
var seriesData = [];
var xCategories = [];
var i, cat;
alert("outside");
$.getJSON(url, function (data) {
alert("inside JSON function");
for (i = 0; i < data.length; i++) {
cat = '' + data[i].period_name;
if (xCategories.indexOf(cat) === -1) {
xCategories[xCategories.length] = cat;
}
}
for (i = 0; i < data.length; i++) {
if (seriesData) {
var currSeries = seriesData.filter(function (seriesObject) {
return seriesObject.name == data[i].series_name;
}
);
if (currSeries.length === 0) {
seriesData[seriesData.length] = currSeries = { name: data[i].series_name, data: [] };
} else {
currSeries = currSeries[0];
}
var index = currSeries.data.length;
currSeries.data[index] = data[i].period_final_value;
}
else {
seriesData[0] = { name: data[i].series_name, data: [data[i].period_final_value] }
}
}
//var chart;
//$(document).ready(function() {
chart = new Highcharts.Chart({
chart: {
renderTo: 'container',
type: 'bar'
},
title: {
text: 'Stacked column chart'
},
xAxis: {
categories: xCategories
},
yAxis: {
//min: 0,
//max: 100,
title: {
text: 'Total fruit consumption'
},
stackLabels: {
enabled: false,
style: {
fontWeight: 'bold',
color: (Highcharts.theme && Highcharts.theme.textColor) || 'gray'
}
}
},
legend: {
align: 'right',
x: -100,
verticalAlign: 'top',
y: 20,
floating: true,
backgroundColor: (Highcharts.theme && Highcharts.theme.legendBackgroundColorSolid) || 'white',
borderColor: '#CCC',
borderWidth: 1,
shadow: false
},
tooltip: {
formatter: function () {
return '<b>' + this.x + '</b><br/>' +
this.series.name + ': ' + this.y + '<br/>'
}
},
series: seriesData
});
});
});
}
In url , values.json is my JSON file as follows
[{"series_name":"Actual","period_name":"Q1 / 2013","period_final_value":17},
{"series_name":"Actual","period_name":"Q2 / 2013","period_final_value":15},
{"series_name":"Actual","period_name":"Q3 / 2013","period_final_value":13},
{"series_name":"Actual","period_name":"Q4 / 2013","period_final_value":19},
{"series_name":"Alarm","period_name":"Q1 / 2013","period_final_value":14.103},
{"series_name":"Alarm","period_name":"Q2 / 2013","period_final_value":14.404499999999999},
{"series_name":"Alarm","period_name":"Q3 / 2013","period_final_value":14.966999999999999},
{"series_name":"Alarm","period_name":"Q4 / 2013","period_final_value":50},
{"series_name":"Target","period_name":"Q1 / 2013","period_final_value":15.67},
{"series_name":"Target","period_name":"Q2 / 2013","period_final_value":16.005},
{"series_name":"Target","period_name":"Q3 / 2013","period_final_value":16.63},
{"series_name":"Target","period_name":"Q4 / 2013","period_final_value":100}]
file renders but data is not shown on chart, only the alert outside the getJSON method works, inner one doesnot works, the same code if I try to run from html page then it works fine, but now I have written the entire code as it is in VS in ASP.NET Web Application and I have called the loadJson function on body onLoad in javascript as follows,
<body onload="loadJson();">
but the method doesn't run,
not able to solve this, any help will be greatly appreciated...
----------Additional work------
when I add my JSON data in any variable above the getJSON method and eliminate the getJSON method and access that then I get the Graph properly but when I am using getJSON method then it's not working
-----Error Inspected----------
I inspected the error in chrome and I got to know it is not able to get the json file, I have kept the JSON file in project folder , then also I tried by keeping the json file in localhost, still its saying same error..
Now I am thinking I am facing problem with mime type handling with aspx page..is it anything to link with it..??

1) Make sure you are using a valid json: www.jsonlint.com
2) Run your json file on localhost. Tell me if you see the json file on your browser run on localhost. Make sure you have this in your web.config
<system.webServer>
<staticContent>
<mimeMap fileExtension=".json" mimeType="application/json" />
</staticContent>
</system.webServer>
3) Alert info using getJSON function
$(document).ready(function () {
$.getJSON("values.json", function (data) {
$.each(data, function () {
alert(this.series_name);
});
});
});
4) When you pass these tests, continue building up your jQuery codes.

Is there any error with the call of file?
try the following:
$.getJSON(url)
.done(function(data) {
alert("INSIDE FUNCTION")
})
.fail(function(jqXHR, textStatus) {
alert("Request failed: " + textStatus);
});
I use this coding style mostly for all jquery ajax (and wrapper) calls, so that I can give the user a response if
the request failed.

Use $.getJSON not $.get like,
$.getJSON(url, function (data) {
alert("inside JSON function");
And Check your json is valid or not (Check a JSON tab is there in your console)

http://jsonlint.com/ found an issue with your JSON
[{"series_name":"Actual","period_name":"Q1 / 2013","period_final_value":17},
{"series_name":"Actual","period_name":"Q2 / 2013","period_final_value":15},
{"series_name":"Actual","period_name":"Q3 / 2013","period_final_value":13},
{"series_name":"Actual","period_name":"Q4 / 2013","period_final_value":19},]
Its not a valid JSON because of the , just before the ] bracket.

Related

Why do I have the error of "Undefined variable: req"?

I want to display a map of the search. But I keep getting "undefined variable: req" notification. What should I change from my following code:
var jQuery_1_8_2 = jQuery.noConflict();
$(function () {
var array = JSON.parse('{!! !empty($total_search_query) ? json_encode($total_search_query) : "[]" !!}');
console.log(array);
$('#map2').vectorMap({
map: 'indonesia-adm1_merc',
backgroundColor: '#ADF3F0',
regionStyle: {
initial: {
fill: '#FFFFFF'
},
hover: {
fill: '#175083'
}
},
zoomButtons: false,
zoomOnScroll: false,
zoomOnClick: false,
zoomMax: 1,
normalizeFunction: 'polynomial',
onRegionClick: function (event, code) {
var url = '{{ route("search", ["q" => $req->input("q"), "province" => ":id"]) }}';
url = url.replace("%3Aid", code.toLowerCase());
window.location.href = url;
},
onRegionTipShow: function (event, label, code) {
var map = $('#map2').vectorMap('get', 'mapObject');
var regionName = map.getRegionName(code);
var a = array.find(a => a.name === myTrim(regionName))['count'];
label.html('<div class="map-tooltip"><h4 class="header">' + regionName + '</h4><p class="description">Total: ' + a + '</p></div>');
}
});
}(jQuery_1_8_2));
The problem is with the $req->input("q") part that you can determine via looking at the error message which complains about $req not being defined. The reason is that in your Laravel code at some place you have stored the result of request() into a variable called $req, which does not exist in this context. This is the view part, while you have probably parsed the result of request() in your controller. As a result you will need
request()->input("q")
instead.

How to get golbal data in main.js file in Vue JS?

following code is from my main.js file. Here I am parsing data from a url using Vue object and it returns some array of data. Now, In the main.js file I have a another GraphChart object and here I need some data from tableData.
How it would be possible? or any other tricks ?
Now I am getting nothing.
var tableData = new Vue({
data: {
items: ''
},
methods: {
graphData: function () {
var self = this;
var testdata= '';
$.get( 'http://localhost:3000/db', function( data ) {
self.items = data;
});
},
},
created: function() {
this.graphData();
},
computed:{
});
new GraphChart('.graph', {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
// series: needs data from ITEMS object
series:items._data.radialChart[1]
}
)
First, you would be able to get the data using tableData.items if you left the creation of the chart where it is. I expect there might be a problem with that though, because the data is retrieved asynchronously, meaning the chart will be created before the data is returned.
It looks like you will need to move the code that creates the chart into the callback that gets your data.
$.get("http://localhost:3000/db", function(data) {
self.items = data;
new GraphChart(".graph", {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
series: self.items._data.radialChart[1]
});
});
Also, you could replace .graph with a Vue reference, but you didn't post your template, so I'm not sure where .graph appears in your template. You might also need to wrap the creation of GraphChart in $nextTick if you continue to use .graph, in which case the code would be
$.get("http://localhost:3000/db", function(data) {
self.items = data;
self.$nextTick(() => {
new GraphChart(".graph", {
stroke: {
width: 24,
gap: 14
},
animation: {
duration: -1,
delay: -1
},
series: self.items._data.radialChart[1]
});
});
});

Converting javascript data to json file

I'm using a TradingView widget to pull charts and the data is coded in this format:
symbols: {
Equities: ['H&P', 'Google'],
},
symbols_description: {
'H&P': ' BATS:HP ',
'Google': 'BATS:GOOG',
}
I want to convert the symbols and the symbols description into dynamic code using json. I'm struggling on how to use a json file instead of hard coded. Thanks in advance. The entire widget code is:
new TradingView.MiniWidget({
container_id: 'tv-miniwidget-2', tabs: ['Equities'],
symbols: {
Equities: ['H&P', 'Google'],
},
symbols_description: {
'H&P': ' BATS:HP ',
'Google': 'BATS:GOOG',
},
width: 240,
large_chart_url: 'http://www.futuresmag.com/page/interactive-charts',
gridLineColor: "#e9e9ea",
fontColor: "#83888D",
underLineColor: "#dbeffb",
trendLineColor: "#4bafe9",
height: 400,
locale: "en"
});
Build data in steps, not all at once
let options = {
container_id: 'tv-miniwidget-2', tabs: ['Equities'],
width: 240,
large_chart_url: 'http://www.futuresmag.com/page/interactive-charts',
gridLineColor: "#e9e9ea",
fontColor: "#83888D",
underLineColor: "#dbeffb",
trendLineColor: "#4bafe9",
height: 400,
locale: "en"
}
// data format
let jsonData = {
symbols: {
Equities: ['H&P', 'Google'],
},
symbols_description: {
'H&P': ' BATS:HP ',
'Google': 'BATS:GOOG',
}
} // get data from server through ajax request or whatever you need
options.symbols = jsonData.symbols
options.symbols_description = jsonData.symbols_description
new TradingView.MiniWidget(options)
To load a json file in a browser, you typically take the following steps :
Make an Ajax call to your json file
Parse the json file once it's been received
Do something with the content of the file once it's parsed
Here's some demo code for how to do that without using any library:
var getJSON = function(url, successHandler, errorHandler) {
// 1. Make an Ajax call to your json file
var xhr = new XMLHttpRequest();
xhr.open('get', url, true);
xhr.onreadystatechange = function() {
var status, data;
if (xhr.readyState == 4) {
status = xhr.status;
if (status == 200) {
// 2. Parse the json file once it's been received
data = JSON.parse(xhr.responseText);
successHandler && successHandler(data);
} else {
errorHandler && errorHandler(status);
}
}
};
xhr.send();
};
getJSON('widgetdata.json', function(data) {
// 3. Do something with the content of the file once it's parsed
var tradingView = new TradingView.MiniWidget(data);
}, function(status) {
// Error handling goes here
});

Using Angular.JS to bind a JSON value to a Syncfusion Circular gauge

I am working on a project using Syncfusion Javascript gauge control to display a weekly pay bonus. The data is stored on a SharePoint list. I wrote a javascript to convert the sharepoint list from XML to JSON.
<script type="text/javascript">
$ajax({
url: "/_api/web/lists/GetByTitle('bonusEntry')/items?$orderby=Date desc&$filter=Department eq 'Meltshop'&$top=1",
type: "GET",
headers: {
"accept":"application/json;odata=verbose",
},
success: function (data) {
var newMsBonus = "";
for(i=0; i < data.d.results.length; i++){
newMsBonus = newMsBonus + "<div>" + data.d.results[i].ACrew + "</div>";
}
$('#oDataanalysisScoreBoard').html(newMsBonus);
},
error: function (error) {
alert("error: " + JSON.stringify(error));
}
})
Then the value is placed in this Div.
<div id="oDataanalysisScoreBoard"></div>
Basically what I would like to do is bind the data to the Syncfusion control which is set up like this:
$("#CircularGauge1").ejCircularGauge({
width: 500,
height: 500,
backgroundColor: "#3D3F3D",
readOnly: false,
scales: [{
ticks: [{
type: "major",
distanceFromScale: 70,
height: 20,
width: 3,
color: "#ffffff"
}, {
type: "minor",
height: 12,
width: 1,
distanceFromScale: 70,
color: "#ffffff"
}],
}]
});
Then the gauge is created inside this:
<div id="CircularGauge1"></div>
The gauge will build but I cannot get the gauge to recieve the value.
If anyone has any ideas on how I can make this work or things I'm doing I would greatly appreciate any input! Thanks everyone!
EDIT:
The synfusion software creates a gauge and changes the needle based on a number value thats given to it. My ajax call pulls a number entered into a Sharepoint list and then displays that in a div.
In the above code snippet you mentioned the passing value as “String”. If you pass the string value to the loop it will concatenate as string value only. But we need to pass the integer value to the Circular Gauge properties(width, height, distancefromscale) to take effect. Hence, change the code snippet with the following.
$.ajax({
url: "/Gauge/GetData",
type: "POST",
success: function (data) {
var newMsBonus = 0;
for (i = 0; i < data.length; i++) {
newMsBonus = newMsBonus + data[i].MajorDistanceFromScale; // Here i have used the MajorScale distanceFromScale value for the demo
}
$('#oDataanalysisScoreBoard').html(newMsBonus);
},
failure: function (error) {
alert("no data available");
}
});
And we have prepared the sample to meet your requirement with the MVC application including the “.mdf” database. We have created the table called “GaugeData” and added the two record. And using the “$.ajax” called the action method “GetData” and received the “JSON” data from the controller. Refer the following code snippet.
View Page:
$.ajax({
url: "/Gauge/GetData",
type: "POST",
success: function (data) {},
failure: function (error) {
}
});
Controller Page:
public class GaugeController : Controller
{
GaugeDataDataContext db = new GaugeDataDataContext();
public JsonResult GetData()
{
IEnumerable data = db.GaugeDatas.Take(500);
return Json(data, JsonRequestBehavior.AllowGet);
}
}
And then assigned the calculated value to the gauge property. Here, I have used the “MajorDistanceFromScale” value read from the database record and assigned to the gauge properties. Refer the following coding snippet.
var distanceValue = parseInt($("#oDataanalysisScoreBoard")[0].innerHTML);
$("#CircularGauge1").ejCircularGauge({
width: 500,
height: 500,
backgroundColor: "#3D3F3D",
readOnly: false,
scales: [{
ticks: [{
type: "major",
distanceFromScale: distanceValue,
height: 20,
width: 3,
color: "#ffffff"
}, {
type: "minor",
height: 12,
width: 1,
distanceFromScale: 70,
color: "#ffffff"
}],
}]
});
And also please refer the below attached sample for more reference.
GaugeListSample

Extjs not able to upload file second time when it was already uploaded

I have a strange behavior of extjs file upload.
The file upload defined as:
items: [{
xtype: 'filefield',
itemId: 'uploadandsign',
buttonText: NG.getLabel('browse'),
buttonOnly: true,
hideLabel: true,
width: 100
}]
If the file uploading is success I show successful label on the screen with remove "X" button:
onOpenFileBrowserChange: function (filefield, newValue, oldValue, eOpts) {
var me = this,
form = filefield.up('form').getForm(),
infoBox = invoiceorigin.down('#fileuploadinfoplaceholder'),
fileDescription,
secondfilefield,
customerFileName = newValue.replace(/^.*[\\\/]/, ''),
draft = me.getDraft(),
isSigned = true,
files = draft.files();
if (filefield.itemId === 'uploadandsign') {
isSigned = false;
secondfilefield = invoiceorigin.down('#uploadnosign');
fileDescription = 'File system, Unsigned';
}
secondfilefield.disable();
if (form.isValid()) {
form.submit({
url: NG.getLatestApiPath('WebInvoice', 'UploadInvoiceFile'),
waitMsg: NG.getLabel('webinvoiceInvoiceOriginUploadingFile'),
success: function (fp, o) {
if (o.result.success) {
var file = o.result.file;
files.add({
fileName: file.fileName,
createDate: file.createDate,
isAttachment: false,
isSigned: isSigned,
fileOrigin: fileDescription,
customerFileName: customerFileName,
invoiceFileOrigin: 'Local'
});
filefield.disable();
infoBox.removeAll();
infoBox.add(Ext.create('NG.view.webinvoice.InformationBox', {
data: {
closable: true,
icon: true,
iconCls: 'n-pdf-icon',
content: '<div class="n-text-overflow" style="width:145px;">' + fileDescription + '<br/>' + customerFileName + '</div>'
}
}));
}
else {
}
},
failure: function (form, action) {
}
});
}
return false;
},
Then if I remove the file from #infobox, the reset() function called:
onRemoveFileClick: function (view) {
var me = this,
invoiceorigin = view.up('invoiceorigin'),
uploadNoSignBtn = invoiceorigin.down('#uploadnosign'),
uploadAndSignBtn = invoiceorigin.down('#uploadandsign'),
infoBox = invoiceorigin.down('#fileuploadinfoplaceholder'),
draft = me.getDraft(),
files = draft.files(),
pagemanager = view.up('webinvoicepagemanager'),
invoiceFilePlace = files.findExact('isAttachment', false);
me.deleteFileConfirmReject(
NG.getLabel('webinvoiceInvoiceOriginDeleteInvoiceFileTitle'),
NG.getLabel('webinvoiceInvoiceOriginDeleteInvoiceFileMsg'),
function (buttonId, text, opt) {
if (buttonId == 'yes') {
infoBox.removeAll();
if (invoiceFilePlace > -1) {
files.removeAt(invoiceFilePlace);
}
me.fillInvoiceOriginStep(pagemanager);
uploadNoSignBtn.reset();
uploadAndSignBtn.reset();
uploadNoSignBtn.enable();
uploadAndSignBtn.enable();
}
});
}
After this action if I will choose the same file.... nothing happens with page... no any change event fired on the page.. However if I choose different file the behavior is OK.
In the ExtJS documentation said that the reset() function have to clear previous files uploads... however it does not helps.
Is any body met such file upload ExtJS behaivour and could help with this issue?
Thanks a lot.
What I tried and worked quite good was to get the file from the form with a typical JS document.getElementsByName('[name you gave]'); and it got perfectly the file uploaded without mattering in wich execution you are in.
Hope it helps.

Categories