Extjs How to access the name of the chart being used by store - ajax

I have a store being used by several charts. I get my data remotely with an ajax call. In the php script that I link it too, I'm just going to change the parameters of my query to adjust for the different charts.
Here's my idea: I pass the title of the chart's panel as a parameter to my php script. That'll tell me which chart it is.
How do I access the title of whatever chart the store is being used by?
var my_store = Ext.create('Ext.data.JsonStore', {
fields: ['project', 'accepted', 'rejected', 'deleted', 'undefined'],
proxy: {
type: 'ajax',
url: 'generate_proj.php',
extraParams: {foo: **chart.id**},
reader: {
type: 'json'
}
},
autoLoad: true,
listeners: {
beforeload: function(store,operation) {
//operation.params.foo = this.idname;
},
load: function(obj,records) {
var text = Ext.decode(obj.responseText);
Ext.each(records,function(rec) {
});
}
}
});
Here's what I've done so far. Getting the name of a single chart/panel is no problem. I want the store to be able to dynamically read the name of what's using it. How?

Somewhere, you have some code that switches between the various charts. During that code, you could do something like
activeChart.getChartStore().proxy.extraParams.foo = activeChart.getId();
where activeChart is whatever reference you have to the chart you are about to show. Then when you load the store, it'll send the correct parameter.

Related

Ideal way to ajax load a view in Drupal 8 with contextual filters

I have a taxonomy called category.
I have a menu with links to each of these taxonomy items.
The Taxonomy page for each of these items has that menu and also contains a view which uses a contextual filter from the URL to filter the content of the view to content with that taxonomy term.
I wanted to Ajax load the view content when one of these menu items is clicked.
I've been able to achieve the desired result by enabling ajax on the view and using the following JavaScript.
(function ($) {
Drupal.behaviors.course_browser = {
attach: function (context, settings) {
// should only be one menu, but guard against 0, and avoid the if statement.
context.querySelectorAll(".menu--categories").forEach((menu) => {
// for each link in the menu
menu.querySelectorAll(".nav-link").forEach((link) => {
// on click
link.addEventListener("click", (event) => {
event.preventDefault();
// fetch the taxonomy term id from menu link
let tid = event.target.dataset.drupalLinkSystemPath.replace(
"taxonomy/term/",
""
);
// make the ajax call
$.ajax({
url: "/views/ajax",
type: "post",
data: {
view_name: "course_browser",
view_display_id: "block_1",
view_args: tid,
},
success: (response) => {
response.forEach((action) => {
// the response contains a number of commands; I'm not sure
if (
action.command === "insert" &&
action.method === "replaceWith"
) {
let viewElement = document.querySelector(VIEW_SELECTOR);
// update the html of the course browser
viewElement.innerHTML = action.data;
// update the url in the browser
window.history.pushState("", "", event.target.href);
// seperate function to adjust my page title
updatePageTitle(event.target.textContent);
// call drupal behaviours passing context to ensure all the other js code gets a chance to manipulate the new content
Drupal.attachBehaviors(viewElement);
}
});
},
error: function (data) {
console("An error occured fetching the course browser");
},
});
});
});
});
},
};
})(jQuery);
I'm looking for feedback on my approach here; my main concern at the moment is the way I handle the response. When I look at the response I receive something like that shown below:
0: {command: "settings", settings: {…}, merge: true}
1: {command: "add_css", data: "<link rel="stylesheet" media="all" href="/core/modules/views/css/views.module.css?qcog4i" />↵"}
2: {command: "insert", method: "append", selector: "body", data: "<script src="/core/assets/vendor/jquery/jquery.min…/js/modules/views/ajax_view.js?qcog4i"></script>↵", settings: null}
3: {command: "insert", method: "replaceWith", selector: ".js-view-dom-id-", data: "The HTML"}
As you can see, I'm manually handling the response by cherry picking the part I want and replacing the HTML of view. Based on what I've seen around Drupal, I think there should be something I can pass this response to that handles it automatically. When I look at the window object of the browser, I can see Drupal.AjaxCommands which looks like it was designed to handle this, but I'm not sure how I should be using this.
I also note that in the case I can simply pass this response to something to have those AjaxCommands executed, the selector ".js-view-dom-id-" isn't right. So I could tweak the response before I pass it, or if someone knows a way to adjust the ajax request to perhaps get the right selector, that would be ideal.
Sorry if this info is readily available somewhere...there are quiet a few resources around related to Drupal and Ajax but I haven't been able to find examples of exactly what I'm doing here, the circumstances always seem to differ enough that I can't use them.
Thanks for any help.

How do I set a value on a Kendo Observable when it is based on a remote datasource?

I need a default value for a field that I get from a datasource, and bind to that field using an observable. (That value can then be updated if needed by the user using a treeview). I can read the initial remote datasource, build the observable and bind the value to the field. I can then pop up a dialog, show a tree and return the values. What I cant seem to do is set the value of the observable because it is based on a datasource, and therefore seems to be a much bigger and more complicated json object which I am viewing in the console. I have also had to bind differently in order to get that working as well as shown below.
Below if just a snippet, but should give an idea. The remote data source returns just: {"name":"a name string"}
<p>Your default location is currently set to: <span id="repName" data-bind="text: dataSource.data()[0].name"></span></p>
<script>
$(document).ready(function () {
var personSource2 = new kendo.data.DataSource({
schema: {
model: {
fields: {name: { type: "string" }}
}
},
transport: {
read: {
url: "https://my-domain/path/paultest.reportSettings",
dataType: "json"
}
}
});
personSource2.fetch(function(){
var data = personSource2.data();
console.log(data.length); // displays "1"
console.log(data[0].name); // displays "a name string"
var personViewModel2 = kendo.observable({
dataSource: personSource2
});
var json = personViewModel2.toJSON();
console.log(JSON.stringify(json));
observName1 = personViewModel2.get("dataSource.data.name");
console.log("read observable: "+observName1);
kendo.bind($(''#repName''), personViewModel2);
});
After a lot of playing around, I managed to get the value to bind using:
data-bind="text: dataSource.data()[0].name"
but I can't find this documented anywhere.
Where I output the observable to the console, I get a great big object, not the simple observable data structure I was expecting. I suspect I am missing something fundamental here!
I am currently just trying to read the observable above, but can't get it to return the string from the json source.
personSource2.fetch(function(){
var data = personSource2.data();
console.log(data.length); // displays "1"
console.log(data[0].name); // displays "Jane Doe"
var personViewModel2 = kendo.observable({
dataSource: personSource2
});
var json = personViewModel2.toJSON();
console.log(JSON.stringify(json));
observName1 = personViewModel2.get("dataSource.data()[0].name");
console.log("read observable: "+observName1);
personViewModel2.set("dataSource.data()[0].name","Another Value");
observName1 = personViewModel2.get("dataSource.data()[0].name");
console.log("read observable: "+observName1);
kendo.bind($(''#repName''), personViewModel2);
});

Using C3.js, when loading data via URL/JSON, is there a way to include groups in the data?

If I'm creating a C3.js graph using:
var chart = c3.generate({
bindto: '#my-chart-div',
data: {
url: '/data/data.json',
mimeType: 'json',
type: 'area',
groups: [
['thing1', 'thing2', 'thing3']
]
},
});
Is there a way for me to include the groupings (thing1, etc) in the URL-loaded JSON data?
I couldn't find a way to include groups in JSON data.
The best work-around I found to to this was using the onrendered callback, and inside that callback, retrieve the data headers from the chart itself, then apply them in the grouping you want using groups:
onrendered: function () {
if ( $('#chart-div').data('stacked') != true ) {
chart.groups( [ chart.data().map(function(x){return x.id}) ]);
$('#chart-div').data('stacked', true);
}
}
Note the line that checks to see if the chart has already been stacked - applying a grouping to the chart re-renders it, which triggers this callback again (prevents an infinite loop).

ExtJS: 2 ajax store, 1 with an extra row

I have this code:
Ext.define('storeBusiness',{
extend: 'Ext.data.Store',
autoLoad: true,
autoSync: true,
model: 'Business',
proxy: {
type: 'ajax',
api: {
read: '../crud/ler_filter.php?db='+database+'&tbl=mercados',
create: '../crud/criar.php?db='+database+'&tbl=mercados',
update: '../crud/update.php?db='+database+'&tbl=mercados',
destroy: '../crud/apagar.php?db='+database+'&tbl=mercados'
},
reader: {
type: 'json',
root: 'rows'
},
writer: {
type:'json'
}
}
});
var storeBusinessCombo = Ext.create('storeBusiness');
var storeBusiness = Ext.create('storeBusiness');
storeBusiness.add({id: 0, business: "All"});
I have 2 grids. One has storeBusiness and the other has storeProducts.
The way the work is when I click on the business grid it filters the produts grid so that it shows the products of that business.
On the business grid it has the storeBusiness that it fetches the records from a database. I want to fetch all business from the database and add one more record (named 'All') without writing it to the database.
I dont want to add 'All' to the database because in the Product's grid I want to have a combobox that has all the business (storeBusinessCombo) without the 'All' record.
Does anyone has any idea how I can do this?
(the code above isn't doing what I want, storeBusiness shows all business without the 'All' in the grid)
Important: This works if the Ext.define('storeBusiness', has a proxy that is of type: 'memory'
Two approaches come to mind:
Add the "all" record to the store after load and don't sync so the
record isn't sent to the server.
Use memory proxy, retrieve the
businesses records via Ajax request and assign them to the store via its data config.
To resolve this I have done:
Put the Ext.define('storeBusiness',{ to autoLoad: false,
Put this code:
var storeBusinessCombo = Ext.create('storeBusiness', {autoLoad: true});
var storeBusiness = Ext.create('storeBusiness');
storeBusiness.on('beforeload', function(){
storeBusiness.loadData([{id: 0, business: "All"}]);
}
And you should put
storeBusiness.load({addRecords: true});
when you want to load storeBusiness.

Create highcharts chart using AJAX/JSON

I am building a website that uses the Highcharts library to display a single line series chart. I am using AJAX to retrieve historical financial data from yahoo finance using their YQL.
The ajax call is working correctly and I can view the returned data in the console for example
console.log( data.query.results.quote[0].Close );
returns the closing price value 457.84
How do I now build the single line series chart using this data?
I cannot find a simple explanation anywhere of how to create the chart using AJAX data.
Thanks
edit: I am fetching the data in AJAX and it works correctly but trying to make the chart work with JSON is where im having difficulties.
This is what my code currently looks like: http://jsfiddle.net/JbGvx/
This is the demo code off the HighStocks website: http://jsfiddle.net/xDhkz/
I think the problem is with the date formatting of the AJAX request. The date is being returned like so 2013-02-25 but the chart wants JS timestamps. Is there a way that I can extract the date from the AJAX, convert it using Date.UTC and then make the chart using the converted data?
If you are considering stock data, consider using HighStocks instead of HighCharts. It can handle many data points much faster than HighCharts is able to.
HighStocks has an example where they pull in AJAX data (1.6 million points) asynchronously here: http://www.highcharts.com/stock/demo/lazy-loading
var chartSeriesData = [];
var chartCategory = [];
$.each(response, function() {
if(this.name!="TOTAL" && this.no!="0")
{
var series_name = this.name;
var series_data = this.no;
var series = [
series_name,
parseFloat(series_data)
];
chartSeriesData.push(series);
}
});
//initialize options for highchart
var options = {
chart: {
plotBackgroundColor: null,
plotBorderWidth: null,
plotShadow: false
},
title: {
text: 'SalesOrder '
},
tooltip: {
pointFormat: '{series.name}: <b>{point.y}</b>'
},
plotOptions: {
pie: {
allowPointSelect: true,
cursor: 'pointer',
center:['60%','60%'],
size:150
,
dataLabels: {
enabled: true,
color: '#000000',
distance: 40,
connectorColor: '#000000',
format: '<b>{point.name}</b>: {point.y} '
}
}
},
series: [{
type: 'pie',
name: 'Browser share',
data:chartSeriesData //load array created from json
}]
}
//options.series[0].setData(datavaluejson);
var chart= $('#container').highcharts(options);

Resources