Multiple Google Charts on Same Page from same Data using Entity model - asp.net

I'm trying to setup a Web Page using the same data that is being pulled for the first chart. Data is being pulled by an edmx entity model. The code below works for single graph. I want to add a Pie Chart on the same page as well using the same data. All the examples I've seen are for graphs using static data. My code is below, I know I would need to just reproduce what I have in some fashion. Thanks,
<script type="text/javascript" src="https://www.google.com/jsapi">
</script>
#section Scripts{
<script>
$(document).ready(function () {
//Load Data Here
var chartData = null;
$.ajax({
url: '/GoogleChart/GetSalesData',
type: 'GET',
dataType: 'json',
data: '',
success: function (d) {
chartData = d;
},
error: function () {
alert('Error!');
}
}).done(function () {
drawChart(chartData);
});
});
function drawChart(d) {
var chartData = d;
var data = null;
data = google.visualization.arrayToDataTable(chartData);
var view = new google.visualization.DataView(data);
view.setColumns([0, {
type: 'number',
label: data.getColumnLabel(0),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(1),
calc: function () { return 0; }
}, {
type: 'number',
label: data.getColumnLabel(2),
calc: function () { return 0; }
}]);
var chart = new google.visualization.ColumnChart(document.getElementById('visualization1'));
var options = {
}
var runFirstTime = google.visualization.events.addListener(chart, 'ready', function () {
google.visualization.events.removeListener(runFirstTime);
chart.draw(data, options);
});
chart.draw(view, options);
}
google.load('visualization', '1', { packages: ['corechart'] });
</script>
<div id="visualization1" style="width:900px; height:500px"></div>
}

first, recommend using...
<script src="https://www.gstatic.com/charts/loader.js"></script>
not...
<script src="https://www.google.com/jsapi"></script>
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
note: the load statement will be the only difference, as seen below...
next, you can draw as many charts as necessary,
after the load statement has completed
you must set a callback to know for sure,
that google charts has loaded all of the requested packages...
multiple packages can be loaded at the same time
google.charts.load('current', {
callback: loadData,
packages: ['corechart', 'table']
});
the callback will also wait for the document to finish loading...
as such, $(document).ready isn't needed
recommend setup similar to following...
<script src="https://www.gstatic.com/charts/loader.js"></script>
#section Scripts{
<script>
function loadData() {
$.ajax({
url: '/GoogleChart/GetSalesData',
type: 'GET',
dataType: 'json',
data: '',
}).fail(function (jq, text, errMsg) {
console.log(text + ': ' + errMsg);
}).done(function (jsonData) {
drawCharts(jsonData);
});
}
function drawCharts(jsonData) {
var chartData = google.visualization.arrayToDataTable(jsonData);
var chartCol = new google.visualization.ColumnChart(document.getElementById('visualization-col'));
chartCol.draw(chartData);
var chartPie = new google.visualization.PieChart(document.getElementById('visualization-pie'));
chartPie.draw(chartData);
var chartTable = new google.visualization.Table(document.getElementById('visualization-table'));
chartTable.draw(chartData);
}
google.charts.load('current', {
callback: loadData,
packages: ['corechart', 'table']
});
</script>
<div id="visualization-col"></div>
<div id="visualization-pie"></div>
<div id="visualization-table"></div>
}
note: each chart has a specific data format
although most of the charts in 'corechart' will be fine,
not all charts may work with the same data table...

Related

WordPress with select2 and Toastr get previous selected value destroys select2 behavior

I am using WordPress and I have used Select2 and Toastr libraries successfully.
Basically I have a dropdown and if I change, Toastr will ask whether I need to update or not.
If I click on "Yes" then it will update and if I click on "No" then my dropdown should set previous value and nothing will happen.
Currently its selecting previous value but then if I open the same dropdown try to click on it to search then its saying "The results could not be loaded".
Here is my JS code what I have done so far.
var prevSubVarClientId;
jQuery('.mySubscription').select2({
allowClear: true,
placeholder: "",
//minimumInputLength: 3,
ajax: {
type: "POST",
url: '/wp-admin/admin-ajax.php',
dataType: 'json',
delay: 250, // delay in ms while typing when to perform a AJAX search
data: function (params, page) {
return {
action: 'list_posts',
q: params.term,
};
},
processResults: function( data ) {
var options = [];
if ( data ) {
jQuery.each( data, function( index, text ) {
options.push( { id: text['id'], text: text['name'] } );
});
}
return {
results: options
};
},
cache: true
}
});
jQuery('.mySubscription').on('select2:selecting', function (evt) {
prevSubVarClientId = jQuery('select').val();
});
jQuery('.mySubscription').change(function() {
var $this = jQuery(this);
jQuery(this).blur();
alertify.confirm("Are you sure you want to transfer?",
function(e){
var subscriptionId = jQuery($this).data("subscription-id");
var url = jQuery($this).data("ajax-url");
var userId = jQuery($this).val();
jQuery.ajax({
type: "POST",
url: url,
data : {
action : 'update_var_client_user_id',
userId : userId,
subscriptionId : subscriptionId
},
success: function(data)
{
var data = JSON.parse(data);
toastr["success"]("Transferred Successfully." );
}
});
},
function(){
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
}).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
});
As you can see I have prevSubVarClientId variable and mySubscription dropdown with this class.
jQuery('.mySubscription').change(function() { here you can see I am opening alertify confirm box and if I click on "No" then I am doing below code.
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
But then whenever I am trying to open the dropdown again, I am getting the below error.
Can some one guide me, what I am doing wrong here ?
Thanks
"The results could not be loaded". only show when return data is null or not found.
I tested your code below snippet and working fine.
$(".js-data-example-ajax").select2();
jQuery('.js-data-example-ajax').on('select2:selecting', function (evt) {
prevSubVarClientId = jQuery('select').val();
});
jQuery('.js-data-example-ajax').change(function() {
var $this = jQuery(this);
jQuery(this).blur();
alertify.confirm("Are you sure you want to transfer?",
function(e){
console.log('change');
},function(){
console.log('no change');
jQuery($this).val(prevSubVarClientId);
jQuery($this).select2().trigger('change');
}).set({title:"Alert!!!"}).set({ labels:{ok:'Yes', cancel: 'No'} });
});
.select2-container, .select2-container--open .select2-dropdown--below {
width: 200px !important;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/css/select2.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.13/js/select2.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/css/alertify.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/AlertifyJS/1.13.1/alertify.min.js"></script>
<select class="js-data-example-ajax">
<option value="abc">ABC</option>
<option value="bca" selected>BCA</option>
<option value="mnp">MNP</option>
<option value="pqr">PQR</option>
</select>

Conversion of eloquent result to use with c3.js

I need to generate a pie chart whose output will be a representation of eloquent output.
My query is:
$data = MyModel::select('province_id', DB::raw('COUNT(id) AS cnt'))
->groupBy('province_id')
->get();
dd($data) gives me:
Then it is passed to blade view as:
return view('tool.charts', ['data' => $data]);
In my blade view (js code is embedded in <script> tag):
var datax = {!! json_encode($data) !!};
var chart = c3.generate({
bindto: '#pie1',
data: {
columns: datax,
type : 'pie',
}
});
But this doesn't draw the pie chart. If I use hardcoded values, like:
var chart = c3.generate({
bindto: '#pie2',
data: {
columns: [
['data1', 30],['data2', 140],['data3', 40],['data4', 170],
],
type : 'pie',
}
});
It shows the chart as expected.
UPDATE:
column was changed to json and still has no luck.
var chart = c3.generate({
bindto: '#pie1',
data: {
json: datax,
type : 'pie',
}
});
First of all, pie chart is a bit different comparing to others (check here similar question).
For your case, I would suggest this:
In your controller, get data as json
public function myjson(Request $request){
$data = MyModel::selectRaw('province_id, COUNT(*) AS cnt')
->groupBy('province_id')
->get();
return response()->json($data->toArray());
}
define a route to access on this controller. Add this to your route:
Route::get('my/json', ['as'=> 'my.json', 'uses'
=>’MyController#myjson']);
Then define your chart inside a blade using AJAX (Not passing variable from controller like you did)
<script language="JavaScript">
$(document).ready(function () {
$.ajax({
type: "GET",
url: '{{route('my.json')}}',
data: "{}",
contentType: "application/json",
dataType: "json",
async: "true",
cache: "false",
success: function (result) {
OnSuccess(result);
},
error: function (xhr, status, error) {
alert(error);
}
});
});
function OnSuccess(response) {
var data = {};
var lists = [];
response.forEach(function (e) {
lists.push(e.province_id);
data[e.province_id] = e.cnt;
});
var chart1 = c3.generate({
bindto: '#pie1',
data: {
json: [data],
type : 'pie',
keys: {
value: lists
}
}
});
};
</script>

Google Charts Category Filter using SQL Server

I'm trying to create a dropdown filter that will allow filtering of chart(s). My webmethod is working (I've tested it using a chart) but my ajax is not returning any rows within the dropdown.
Any help really appreciated
<script type="text/javascript">
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(drawCountryChart);
google.setOnLoadCallback(drawDivisionChart);
var dashboard = new google.visualization.Dashboard(
document.getElementById('Dashboard'));
function drawCountryChart() {
$.ajax({
type: "POST",
url: "Season.aspx/GetCountry",
data: '{}',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (r) {
var CountryData = google.visualization.arrayToDataTable(r.d);
var namePicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'ddlCountry',
'options': {
'filterColumnLabel': 'CountryName',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
}
if you just want to draw the filter on its own,
need to assign the data table property and call the draw method...
var CountryData = google.visualization.arrayToDataTable(r.d);
var namePicker = new google.visualization.ControlWrapper({
'controlType': 'CategoryFilter',
'containerId': 'ddlCountry',
'dataTable': CountryData, // <-- assign data table
'options': {
'filterColumnLabel': 'CountryName',
'ui': {
'labelStacking': 'vertical',
'allowTyping': false,
'allowMultiple': false
}
}
});
namePicker.draw(); // <-- draw control
note: recommend not using the older chart library --> jsapi
according to the release notes...
The version of Google Charts that remains available via the jsapi loader is no longer being updated consistently. Please use the new gstatic loader.js from now on.
<script src="https://www.gstatic.com/charts/loader.js"></script>
this will only affect the load and callback statements,
in fact, the callback can be added to the load statement directly...
google.charts.load('current', {
callback: function () {
drawCountryChart();
drawDivisionChart();
},
packages:['corechart', 'controls']
});

jquery loading animation issue

I'm trying to hide the menu, show animated gif, hide gif, return updated menu.
The menu disappears and reappears, but the animated gif won't show.
What am I doing wrong?
$(document).ready(function () {
$("#menu").wijmenu({
orientation: 'vertical'
});
$("#TDButtons a").click(function () {
var href = $(this).attr("href");
$('#menuAjax').hide(0, LoadAjaxContent(href));
return false;
});
function LoadAjaxContent(href) {
$.ajax({
url: href,
success: function (data) {
$("#menuAjax").html(data)
.addClass("loading")
.delay(5000)
.removeClass("loading")
.fadeIn('slow');
$("#menu").wijmenu({
orientation: 'vertical'
});
}
});
}
Please let me know if you need more info. Thanks
It doesn't show cause you are delaying something that isn't a queueable animation:
.addClass("loading")
.delay(5000)
.removeClass("loading")
.fadeIn('slow');
is interpreted like:
.addClass("loading")
.removeClass("loading")
.delay(5000)
.fadeIn('slow');
You could do:
function LoadAjaxContent(href) {
$.ajax({
url: href,
success: function (data) {
$("#menuAjax").html(data).removeClass("loading").fadeIn('slow');
$("#menu").wijmenu({ orientation: 'vertical' });
}
});
}
$("#TDButtons a").click(function (e) {
e.preventDefault();
var href = this.href;
$('#menuAjax').addClass("loading").hide();
LoadAjaxContent(href);
});
You are adding, removing the loading class from the element once the data is already received. You should do it with ajaxStart and ajaxStop function which eventually adds the loading class before the request is send and removes once the ajax operation is completed.
$(document).ready(function () {
$("#menu").wijmenu({
orientation: 'vertical'
});
$("#TDButtons a").click(function () {
var href = $(this).attr("href");
$('#menuAjax').hide(0, LoadAjaxContent(href));
return false;
});
$.ajaxStart(function(){
$("#menuAjax").addClass("loading");
});
$.ajaxStop(function(){
$("#menuAjax").removeClass("loading");
});
function LoadAjaxContent(href) {
$.ajax({
url: href,
success: function (data) {
$("#menuAjax").html(data)
.delay(5000)
.fadeIn('slow');
$("#menu").wijmenu({
orientation: 'vertical'
});
}
});
}
You have your loading the wrong way round
Your class of loading should be added before the request is sent, and then removed after. You are adding it, (and as roXon pointed out using the .delay function incorrectly) and then removing it again, not giving it any time to be shown.
Try something like this
$(document).ready(function () {
$("#menu").wijmenu({
orientation: 'vertical'
});
$("#TDButtons a").click(function () {
var href = $(this).attr("href");
$('#menuAjax').hide(0, LoadAjaxContent(href));
return false;
});
function LoadAjaxContent(href) {
$("#menuAjax").addClass("loading")
$.ajax({
url: href,
success: function (data) {
$("#menuAjax").html(data)
//.delay(5000) Not needed!
.removeClass("loading")
.fadeIn('slow');
$("#menu").wijmenu({
orientation: 'vertical'
});
}
});
}

Jquery AutoComplete Load Problem

Not Work
Jquery Code:
$('[id$=Name]').autocomplete('CallBack.aspx',{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
Json:
var data = [{NAME:"John",AGE:"57"}];
Work
Jquery Code:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete(data,{formatItem: function(item){return item.Name;}}).result(function(event, item) {
location.href = item.AGE;
});
alt text http://img11.imageshack.us/img11/119/38235621.jpg
Help me pls how its make ? callback.aspx return json not work
Try changing your data to this:
var data = [{id:"John",value:"57"}];
EDIT
Here's a sample of what I think you're trying to do:
var data = [{NAME:"John",AGE:"57"}];
$('[id$=Name]').autocomplete('CallBack.aspx', {
formatItem: function(item) {
return item.NAME;
}}).result(function(event, item) {
location.href = 'somepage.aspx?age=' + item.AGE;
});
Basically you needed to capitalise return item.Name to return item.NAME.
Try This
<script type="text/javascript">
$(document).ready(function () {
$("#TextboxId").autocomplete({
source: function (request, response) {
$.ajax({
url: "URL",
type: "POST",
dataType: "json",
data: { ids: idstopass },
success: function (retrieveddata) {
alert(retrieveddata);
var dData = JSON.parse(retrieveddata);
alert(dData.Name);
},
error: function (request, status, error) {
console.log("Error! " + request.responseText);
}
})
},
});
})
</script>

Resources