I used the following code to fetch JSON data which was a success. I initialized a global array and stored one unit of that data in an array. Now somewhere in my code, there is an array nested inside an object how do I pass this array there?
var myRequest = new Request("https://script.googleusercontent.com/macros/echo?user_content_key=KW75vuIX25SoStm_K2HLVQNBRF2fx_5URDdL-vYJfUSTBaOAlMkJeWc25wjo5zdMLaznziyuqNd4B5kNs8k3tH0OxgnfssPwm5_BxDlH2jW0nuo2oDemN9CCS2h10ox_1xSncGQajx_ryfhECjZEnIFtsXaNuh0rFflir-T-GWuA8AvQ2kUI-jEwpZssg8RaEHh5W9MAfgDGMRkNsN06wEWY2nZ7HPw5&lib=M_p61mp1Qy6uGkXTBzlj4kloBXIZCdEN3")
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++)
{
arr[i]=data.user[i].battingScore;
}
return arr;
});
This is where I want to use the arr:
document.addEventListener('DOMContentLoaded', function () {
document.addEventListener('DOMContentLoaded', function () {
var myChart3 = Highcharts.chart('c', {
title: {
text: 'Logarithmic axis demo'
},
xAxis: {
tickInterval: 1,
type: 'logarithmic'
},
yAxis: {
type: 'logarithmic',
minorTickInterval: 0.1
},
tooltip: {
headerFormat: '<b>{series.name}</b><br />',
pointFormat: 'x = {point.x}, y = {point.y}'
},
series: [{
data:[], //here
pointStart: 1
}]
});
});
});
Note: Here, series is an array of objects but is an attribute of hello object. I want the values of arr inside data which is an array. How to do that?
If you want to gather the data before rendering the chart, you could do this.
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++){
arr[i]=data.user[i].battingScore;
}
return arr;
})
.then(function(scores){
document.addEventListener('DOMContentLoaded', function () {
var myChart3 = Highcharts.chart('c', {
. . .
series: [{
data:scores,
pointStart: 1
}]
});
});
});
});
Otherwise, you can define your myChart3 as a global variable and change "var myChart3=" to just "myChart3=" in your event listener. Then, you can populate the data into the existing chart using series.addPoint like this:
var myChart3;
document.addEventListener('DOMContentLoaded', function () {
myChart3 = Highcharts.chart('c', {
. . .
});
});
fetch(myRequest)
.then(function(res){
return res.json();
})
.then(function(data){
for(var i=0;i<400;i++){
myChart3.series[0].addPoint(data.user[i].battingScore, false);
}
myChart3.redraw();
},
cache: false
});
Related
My ajax is like this :
<script>
new Vue({
...
methods: {
fetchItems: function (page) {
var data = {page: page};
this.$http.get('api/items', data).then(function (response) {
console.log(JSON.stringify(response))
this.$set(this, 'items', response.data.data.data);
this.$set(this, 'pagination', response.data.pagination);
}, function (error) {
// handle error
});
},
...
}
});
</script>
My routes is like this :
Route::get('/api/items/', function () {
dd(Input::get('page'));
$results = \App\Post::latest()->paginate(7);
$response = [
'pagination' => [
'total' => $results->total(),
'per_page' => $results->perPage(),
'current_page' => $results->currentPage(),
'last_page' => $results->lastPage(),
'from' => $results->firstItem(),
'to' => $results->lastItem()
],
'data' => $results
];
return $response;
});
When executed, I check on the console, the result = null, whereas I had put this : dd(Input::get('page'));
Should it display page who sended
How can I solve it?
Try changing the line:
dd(Input::get('page'));
to:
return Input::get('page');
The dd method will dump a var value and halt the execution. So the output won't be a properly formatted json. It will probably be some raw html displaing the value you dumped.
This is full example of vue js code
var app = new Vue({
el: '#invoice',
data: {
form: new FormData(),
errors: {},
tax: 0
},
methods: {
random: function () {
this.form.serial = Math.floor(Math.random() * 1000000) + 1;
},
sortBy: function() {
if(this.form.tax_id) {
var url = '{{route('invoice.get_tax', null)}}';
this.$http.get(url)
.then(function(response){
if(response.data) {
console.log(response.data)
}
});
}
}
})
There is the route
Route::get('/get_tax/{tax_id}', function($tax_id)
{
$tax = App\Tax::findOrFail($tax_id);
if ($tax) {
return response()
->json([
'rate' => $tax->rate,
'type' => $tax->type
], 200);
} else {
return response()
->json([
'rate' => 0,
'type' => 1
], 200);
}
})->name('invoice.get_tax');
How to recover the elements of a foreach for reformed in this way:
['julie','nicola','sahra']
My code
var outPutStats = ''
client.data.forEach(function(element) {
outPutStats += [element.name];
});
.............................
.............................
xAxis: {
name: [outPutStats] // Must be ['dataName1','dataName2']
},
yAxis: {
title: {
text: null
}
},
try this:
var outputStats = [];
client.data.forEach(function(element) {
outputStats.push(element.name);
});
It's probably more semantically accurate to use Array#map instead, though, if the clients you want support it (which afaik they should if they support forEach):
var outputStats = client.data.map(function(element) { return element.name; });
If you want to copy client.data into a new array outPutStats then this will work (although I don't see the reason why, you could just use client.data):
// This must be an array
var outPutStats = [];
client.data.forEach(function(element) {
// fill the array with elements
outPutStats.push(element.name);
});
// ...
// ...
xAxis: {
name: outPutStats // outPutStats is already an array
},
yAxis: {
title: {
text: null
}
},
Kind of lost when iterating over promises, im trying to transform this:
[{
' site' : ['url', 'url', 'url']
},
{
' site' : ['url', 'url', 'url']
}]
so that it becomes:
[{
'site' : [{ 'url' : result_of_function }, { 'url' : result_of_function }, { 'url' : result_of_function }]
},
{
'site' : [{ 'url' : result_of_function }, { 'url' : result_of_function }, { 'url' : result_of_function }]
}]
So far I created the function below, but for some reason checkBranding is not called.
function searchPageArray(brand, siteObjArr) {
return Promise.map(siteObjArr, function(sitesObj){
var k = Object.keys(sitesObj)[0]
var urlArr = sitesObj[k];
return Promise.map(urlArr, function(url){
return searchPage(url).then(function(html){
var tempObj = {}
tempObj[url] = checkBranding(url, html, brand)
return tempObj
})
})
return sitesObj;
})
}
Thanks for the help!
You can use bluebird.js's props() method.
// You must use bluebird to achieve this
var Promise = require('bluebird');
function searchPageArray(brand, siteObjArr) {
return Promise.map(siteObjArr, function (sitesObj) {
var k = Object.keys(sitesObj)[0]
var urlArr = sitesObj[k];
return Promise.map(urlArr, function (url) {
return searchPage(url)
.then(function (html) {
// Use promise.props(). It resolves all properties of a
// object before returning. If there are any properties that
// arent promises they are returned as normal.
return Promise.props({
url: checkBranding(url, html, brand) // Assuming checkBranding() returns a promise.
});
});
});
return sitesObj;
});
}
I'm trying to use high charts via angular to take advantage of double binding. I'm having an issue rendering the data, the graph works but the data is not showing up in the chart. When I check the DOM console I can get the array but for some reason its not showing up in the graph.
cpvmPartners = [];
cpvmPlannedCpm = [];
actualCpm = [];
graphData = [];
cpvm = [];
plannedPrepared = [];
getData = function(){
$.getJSON('/cpvmdata', function(data) {
for(k in data){
if(data[k]['audience'] == 'GCM'){
graphData.push([data[k]['partner'],data[k]['plannedcpm']])
actualCpm.push(Math.round((data[k]['mediacost']/data[k]['impressions']*1000)))
cpvmPlannedCpm.push(data[k]['plannedcpm'])
cpvmPartners.push(data[k]['partner'])
}
}
});
}
prepareData = function(){
for(var i = 0; i < actualCpm.length; i++) {
actualPrepared.push({name: "CPM", data: actualCpm[i]})
plannedPrepared.push({name: "Planned CPM", data: cpvmPlannedCpm[i]})
}
}
myApp = angular.module('main', ['highcharts-ng']);
myApp.controller('graphController', function ($scope) {
getData();
prepareData();
$scope.highchartsNG = {
options: {
chart: {
type: 'bar'
}
},
series: [{
data: actualCpm
}],
title: {
text: 'Hello'
},
loading: false
}
});
So the getData() function you call in the angular controller is asynchronous:
By the time you have gotten the data, you have already made your chart in $scope.highChartNg
That is why you can see your data the console but you don't actually set it to the actualCpm by the time angular is done. To fix this you need to create the chart IN your $.getJSON function like so:
var options = {
chart: {
renderTo: 'container',
type: 'spline'
},
series: [{}]
};
$.getJSON('data.json', function(data) {
options.series[0].data = data;
var chart = new Highcharts.Chart(options);
});
You can see more here: http://www.highcharts.com/docs/working-with-data/custom-preprocessing
Easier just to use
$http.get
Angular service.
Blending jQuery and Angular is troublesome for scoping.
$http.get('cpvmdata')
.then(function(response){
$scope.output = response.data;
for(k in $scope.output){
if($scope.output[k]['audience'] == 'GCM'){
$scope.planned.push($scope.output[k]['plannedcpm'])
$scope.partners.push($scope.output[k]['partner'])
$scope.cpm.push(Math.round(($scope.output[k]['mediacost']/$scope.output[k]['impressions']*1000)))
}
}
});
I'm using Angular-nvD3. I have a simple chart that looks like this:
HTML:
<nvd3 options="options" data="data"></nvd3>
JS:
$scope.options = {
chart: {
type: 'pieChart',
height: 450,
x: function (d) { return d.key; },
y: function (d) { return d.y; },
showLabels: true,
duration: 1100,
showLegend: false
}
};
My data object is just a simple array of objects with key and y properties. On some DOM event, I update the data from the server and change the data object. When I do this, my chart is resized.
Why is this happening and how can I prevent it?
Update:
// This is the function that is called on the DOM event.
var loadAllData = function () {
var result = getData();
result.$promise.then(function (returnedAmounts) {
loadChartsData(returnedAmounts.expenses, $scope.data);
}, function (error) {
// Error.
});
}
var loadChartsData = function (group, chartsData) {
// Iterate over the group
for (var i = 0; i < group.length; i++) {
chartsData[i] = {
key: group[i].name || group[i].key,
y: group[i].amount
};
}
}
try to set your config.deepWatchData = false, that way the chart will only update when you tell it to. (by using api.refresh)