In my Yii web application, Google chart is not working. I am getting all values by renderpartial method. But, the pie chart is not displayed.
My code is,
<div class="content">
<div id="graph" style="width:300px;height:300px ">
</div>
</div>
<script type="text/javascript" src="https://www.google.com/jsapi">
// Load the Visualization API and the piechart package.
google.load("visualization", "1", { packages: ["corechart"] });
// Set a callback to run when the Google Visualization API is loaded.
google.setOnLoadCallback(createPIE);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function createPIE() {
var options = {
title: 'Fees Allocation',
colors: ['#888', 'orange','red'],
is3D: true
};
// Create our data table.
var data = google.visualization.arrayToDataTable([
['Total Amount', <?php echo $amount;?>],
['Collected', <?php echo $collected;?>],
['Due', <?php echo $due;?>]]);
var chart = new google.visualization.PieChart(document.getElementById('graph'));
chart.draw(data, options);
}
</script>
Please help me.
There are few mistakes in your code please try below code
<?php
$amount = 20;
$collected = 50;
$due = 30;
?>
<div class="content">
<div id="graph" style="width:300px;height:300px">
</div>
</div>
<script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script>
<script type="text/javascript">
// Load the Visualization API and the piechart package.
google.charts.load("current", { packages: ["corechart"] });
// Set a callback to run when the Google Visualization API is loaded.
google.charts.setOnLoadCallback(createPIE);
// Callback that creates and populates a data table,
// instantiates the pie chart, passes in the data and
// draws it.
function createPIE() {
var options = {
title: 'Fees Allocation',
colors: ['#888', 'orange','red'],
is3D: true
};
// Create our data table.
var data = google.visualization.arrayToDataTable([
['status', 'Amount'],
['Total Amount', <?php echo $amount;?>],
['Collected', <?php echo $collected;?>],
['Due', <?php echo $due;?>]]);
var chart = new google.visualization.PieChart(document.getElementById('graph'));
chart.draw(data, options);
}
</script>
Checkout this fiddle : https://jsfiddle.net/xoevL26z/
Related
Using the new jsPDF .html() pretty much pulled straight from their docs, but it still results in a blank page:
Results in blank page:
function saveDoc() {
window.html2canvas = html2canvas
const doc = document.getElementById('doc')
if (doc) {
var pdf = new jsPDF('p', 'pt', 'a4')
pdf.html(doc.innerHTML, {
callback: function (pdf) {
pdf.save('DOC.pdf');
}
})
}
}
Results in no PDF generated:
function saveDoc() {
window.html2canvas = html2canvas
const doc = document.getElementById('doc')
if (doc) {
var pdf = new jsPDF('p', 'pt', 'a4')
pdf.html(doc.innerHTML, {
function (pdf) {
pdf.save('DOC.pdf');
}
})
}
}
Also results in blank page:
function saveDoc() {
window.html2canvas = html2canvas
const doc = document.getElementById('doc')
if (doc) {
var pdf = new jsPDF('p', 'pt', 'a4')
pdf.html(doc, {
callback: function (pdf) {
pdf.save('DOC.pdf');
}
})
}
}
Will use another tool if there are any other suggestions. Need it to be secure and generate selectable text PDF to keep overall size down. It's a long document it's generating and when doing it via addImage() the resulting file is huge. Thoughts?
After trying whole day came with following solution. I think we are getting blank page because of versions of html2canvas. I was using updated jspdf(1.5.3) with html2canvas(1.0.0-rc.3). Due to this I was getting blank pdf. When I use html2canvas(1.0.0-alpha.12) with jspdf(1.5.3) I am getting pdf with contents(not blank). So better to change version of html2canvas in order to work with newly .html() method.
// scripts included
<script type="text/javascript" src="html2canvas.js"></script> // 1.0.0-alpha.12 downloaded
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.5.3/jspdf.debug.js" integrity="sha384-NaWTHo/8YCBYJ59830LTz/P4aQZK1sS0SneOgAvhsIl3zBu8r9RevNg5lHCHAuQ/" crossorigin="anonymous"></script>
//html
<div id='doc'>
<p>Hello world</p>
<div class="first-page">
<h1>bond</h1>
<img src="1.png"/>
</div>
<div class="second-page">
<img src="2.png"/>
</div>
</div>
<button onclick="saveDoc()">click</button>
// javascript
<script type="text/javascript">
var pdf = new jsPDF('p', 'pt', 'a4');
function saveDoc() {
window.html2canvas = html2canvas
const doc = document.getElementsByTagName('div')[0];
if (doc) {
console.log("div is ");
console.log(doc);
console.log("hellowww");
pdf.html(document.getElementById('doc'), {
callback: function (pdf) {
pdf.save('DOC.pdf');
}
})
}
}
</script>
html2canvas 1.0.0 alpha.12
.html() not working github
For me the working solution was to add the callback/promise behavior --- pdf.html(doc).then(() => pdf.save('fileName.pdf')); Seems that html() method works async and the file to be downloaded was not ready when downloading based on the other example --- that's why it was empty.
The plugin Vue-Select.
What I was trying to do is, make a search-select-dropdown input based on database.
So here's my SQL first named Ms_Location.
id_Loc | name_Loc
LOC0001 | Indonesia
LOC0002 | China
LOC0003 | America
My index.php
<!DOCTYPE html>
<html>
<head>
</head
<body>
<div class="form-group">
<label for="lokasi_id" class="control-label required"><strong>Lokasi</strong></label>
<v-select :options="lokasi_list" placeholder='Type location..'></v-select>
</div>
<script type="text/javascript" src="js/vue.js"></script>
<script src="https://unpkg.com/vue-select#latest"></script>
Vue.component('v-select', VueSelect.VueSelect);
var app = new Vue ({
el: '#app',
data: {
lokasi_select: '',
lokasi_list: [],
},
// End of data
computed: {
get_lokasi() {
var list_loc = new Array();
list_loc = <?php include('receive_lokasi.php') ?>;
for(var i=0; i<list_loc.length; i++) {
var pushLoc = {
label: list_loc[i][1], value: list_loc[i][0]
}
this.lokasi_list.push(pushLoc);
}
return list_loc[0][1];
}
}
})
});
</script>
</body>
</html>
And this is my receive_lokasi.php
<?php
include ('koneksi.php');
$condition = "1";
if(isset($_GET['userid'])){
$condition = " id=".$_GET['userid'];
}
$sqltran = mysqli_query($con, "SELECT id_Loc, name_Loc FROM ms_location")or die(mysqli_error($con));
$response = array();
while ($rowList = mysqli_fetch_array($sqltran,MYSQLI_NUM)) {
$response[] = $rowList;
}
echo json_encode($response);
mysqli_close($con);
?>
However, I can't seem to get the option shown. This only happens after I make the get_lokasi(). So the mistake is probably there? Or perhaps I was missing something.
I've tried to print the lokasi_list somewhere, and yes, the value is there, but not shown in the dropdown bar.
Also, I'm new to Vue, so any help would be good. Thanks!
Nevermind..
My mistake, I didn't notice my receive_lokasi.php code
Instead of using MYSQLI_NUM
while ($rowList = mysqli_fetch_array($sqltran,MYSQLI_NUM)) {
$response[] = $rowList;
}
I should be using MYSQLI_ASSOC, as documented in here.
while ($rowList = mysqli_fetch_array($sqltran,**MYSQLI_ASSOC**)) {
$response[] = $rowList;
}
After that change this
<v-select :options="lokasi_list" placeholder='Type location..'></v-select>
To this
<v-select label='nama_Location' :options="lokasi_list" placeholder='Type location..'></v-select>
After that, everything loads fine.
Vue's computed properties aren't normally used to populate vue data attributes, they normally take one or more data attributes and combine them into something different for the template to use.
In your code you've tried to populate the vue data attribute 'lokasi_list' in the computed property 'get_lokasi', but you never call 'get_lokasi' anywhere in the template so lokasi_list remains empty.
Another approach to this sort of situation is to use a vue method to fetch data from the php backend via an ajax call with something like axios, and you'd normally use that method in the vue app's created life cycle event to get the data asap.
e.g.
<script>
Vue.component('v-select', VueSelect.VueSelect);
var app = new Vue({
el: '#app',
data: {
lokasi_select: '',
lokasi_list: [],
},
created: function() {
this.fetchLocations();
},
methods: {
fetchLocations: function() {
axios.get('/api/locations-end-point')
.then((response) => {
this.lokasi_list = response.data //might need to change this to match how your php is returning the json
})
.catch((error) => {
//handle the error
})
}
}
});
</script>
Sorry to mention this, but in your php you've got:
if(isset($_GET['userid'])){
$condition = " id=".$_GET['userid'];
}
That looks like you were planning to use it as part of your sql, but it would have been vulnerable to SQL injection attacks, sorry If I'm pointing out something you already knew.
The below example which is given in Google Developers, is working in Chrome/Firfox with out having any issues but not in IE and I am using IE Version#11 (Latest) in windows 8.1.
The chart is not displaying in IE and it a java script error i am getting.![enter image description here][1]
Note:
1. Similar error i am getting when i use Google Developers-JSON example also...to fetch the records from Bigquery and showing in a table...like executing in chrome/firefox but not in IE???
2. If possible Can you please provide and ASP.NET web application example, to connect google BigQuery and showing the Data in GRIDView with C#.NET (NOT WITH ASP.NET MVC)
<html>
<head>
<script src="https://apis.google.com/js/client.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
google.load('visualization', '1', { packages: ['geochart'] });
</script>
<script>
// UPDATE TO USE YOUR PROJECT ID AND CLIENT ID
var project_id = 'XXXXXXXXX';
var client_id = 'XXXXXXXXXXXXXXXXXXXXXX.apps.googleusercontent.com';
var config = {
'client_id': client_id,
//'P12_KEY': 'Keys/ab2c867e84d6d629f0a80595ae14fdbe44492de8 - privatekey.P12',
//'SERVICE_ACCOUNT' : '87853623787-7lsfbcuu9p3gr9o76opp5fkrvhdf0itk#developer.gserviceaccount.com',
'scope': 'https://www.googleapis.com/auth/bigquery'
};
function runQuery() {
var request = gapi.client.bigquery.jobs.query({
'projectId': project_id,
'timeoutMs': '30000',
'query': 'SELECT state, AVG(mother_age) AS theav FROM [publicdata:samples.natality] WHERE year=2000 AND ever_born=1 GROUP BY state ORDER BY theav DESC;'
});
request.execute(function (response) {
console.log(response);
var stateValues = [["State", "Age"]];
$.each(response.result.rows, function (i, item) {
var state = item.f[0].v;
var age = parseFloat(item.f[1].v);
var stateValue = [state, age];
stateValues.push(stateValue);
});
var data = google.visualization.arrayToDataTable(stateValues);
var geochart = new google.visualization.GeoChart(
document.getElementById('map'));
geochart.draw(data, { width: 556, height: 347, resolution: "provinces", region: "US" });
});
}
function auth() {
gapi.auth.authorize(config, function () {
gapi.client.load('bigquery', 'v2', runQuery);
$('#client_initiated').html('BigQuery client initiated');
});
$('#auth_button').hide();
}
</script>
</head>
<body>
<h2>Average Mother Age at First Birth in 2000</h2>
<button id="auth_button" onclick="auth();">Authorize</button>
<button id="query_button" style="display:none;" onclick="runQuery();">Run Query</button>
<div id="map"></div>
</body>
</html>
Perhaps because you have console.log() statement and IE doesn't like that.
The full text of this question is available with a screenshot here
Thanks for any help - original post follows:
So I downloaded the MvcMusicStore and fired up the completed project. I read all the articles talking about extending the view engine and using jquery plugins but I wanted to believe it could be simpler than that to just change the CSS file path when a link gets clicked. Mainly because I didn't want to copy code verbatim that I didn't fully understand. I'm very new to MVC.
So this is what I did:
To HomeController.cs I added:
public ActionResult Theme(string themeName)
{
ViewBag.Theme = ThemeModel.GetSetThemeCookie(themeName);
return View();
}
to Models I added this class:
public class ThemeModel
{
public static string GetSetThemeCookie(string theme)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("userTheme");
string rv = "Blue";
if (theme != null)
rv = theme;
else
{
if (cookie != null)
rv = cookie["themeName"];
else
rv = "Blue";
}
cookie = new HttpCookie("userTheme");
HttpContext.Current.Response.Cookies.Remove("userTheme");
cookie.Expires = DateTime.Now.AddYears(100);
cookie["themeName"] = rv;
HttpContext.Current.Response.SetCookie(cookie);
return rv;
}
}
I then created 2 copies of Site.css, changing only the background color and font-family and a view to generate my link tag.
<link href="#Url.Content(string.Format("~/Content/{0}.css", ViewBag.Theme))" rel="stylesheet" type="text/css" />
Finally, I made these changes to my _Layout.cshtml.
<!DOCTYPE html>
<html>
<head>
<title>#ViewBag.Title</title>
#if (ViewBag.Theme == null) {Html.RenderAction("Theme", "Home");}
<script src="#Url.Content("~/Scripts/jquery-1.4.4.min.js")"
type="text/javascript"></script>
</head>
<body>
<div id="header">
<h1>ASP.NET MVC MUSIC STORE</h1>
<ul id="navlist">
<li class="first">Home</li>
<li>Store</li>
<li>#{Html.RenderAction("CartSummary", "ShoppingCart");}</li>
<li>Admin</li>
</ul>
</div>
#{Html.RenderAction("GenreMenu", "Store");}
<div id="main">
#RenderBody()
</div>
<div id="footer">
Themes: #Ajax.ActionLink("Coral", "Theme", "Home", new { themeName = "Coral" }, null, new { #style = "color : coral"} )
#Ajax.ActionLink("Blue", "Theme", "Home", new { themeName = "Blue" }, null, new { #style = "color : blue;"})
</div>
</body>
</html>
When I run the app I get the general layout rendered twice. Once with only the genre menu rendered on the left and nothing in the body. And then again with the top 5 albums. I can't post the image as I don't have enough rep.
When I click my Coral and Blue links, my theme changes and I get just the one set without the top 5 albums.
So after some more reading on here I tried this:
_Layout.cshtml:
#{Html.RenderAction("Theme", "Home");}
HomeController.cs
public ActionResult Theme(string themeName)
{
ViewBag.Theme = ThemeModel.GetSetThemeCookie(themeName);
return PartialView();
}
But even though this stops the duplicate rendering, when I click the theme link, the colour changes but I get absolutely nothing else on the page.
Well and truly flummoxed now and could really use some help.
Cheers,
.pd.
Okay - here's how I did it in the end.
Create a javascript file. Mine's called master.js:
function ajaxSuccSetTheme(theme) {
$('#linkTheme').attr('href', '/Content/' + theme + '.css');
}
Modify the _Layout.cshtml:
#{
if (ViewBag.Theme == null) {
ViewBag.Theme = MvcMusicStore.Models.ThemeModel.GetSetThemeCookie();
}
}
<link id="linkTheme" href="#Url.Content(string.Format("~/Content/{0}.css", ViewBag.Theme))" rel="stylesheet" type="text/css" />
<script src="#Url.Content("~/Scripts/jquery-2.0.3.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")" type="text/javascript"></script>
<script src="#Url.Content("~/Scripts/master.js")" type="text/javascript"></script>
Notes on this:
The first time the page loads Theme will not have been written to the ViewBag
Give the <link> tag the same ID as the jQuery selector in your js file above
Update unobtrusive ajax jQuery file to the same version as your jQuery lib. Your Ajax.ActionLink won't work without it.
Then my theme switching links in _Layout.cshtml look like this:
<div id="footer">
Themes :
#Ajax.ActionLink("Coral", "Theme", "Home", new { themeName = "Coral" },
new AjaxOptions { HttpMethod = "POST", OnSuccess = string.Format("ajaxSuccSetTheme('{0}');", "Coral")},
new { #style = "color : coral;" }) |
#Ajax.ActionLink("Blue", "Theme", "Home", new { themeName = "Blue" },
new AjaxOptions { HttpMethod = "POST", OnSuccess = string.Format("ajaxSuccSetTheme('{0}');", "Blue")},
new { #style = "color : blue;" })
</div>
Notes on that:
themeName = "whatever" is the argument to your Theme Controller method. this gets passed to the cookie method in the ThemeModel
method = POST so IE doesn't cache it and I've read a couple other questions that got solved by not doing a GET
you have to kludge your own args to the OnSuccess js callback
Next the HomeController.cs change:
public ActionResult Theme(string themeName)
{
ViewBag.Theme = ThemeModel.GetSetThemeCookie(themeName);
if (Request.IsAjaxRequest())
{
return PartialView();
}
else
{
return null;
}
}
Honestly, it doesn't matter if you just return null without checking for IsAjaxRequest() cuz all we need from this is to set the cookie so it remembers when you next login.
Which just leaves the cookie setting method in the ThemeModel:
public class ThemeModel
{
public static string GetSetThemeCookie(string theme = null)
{
HttpCookie cookie = HttpContext.Current.Request.Cookies.Get("userTheme");
string rv = "Blue";
if (theme != null)
rv = theme;
else
{
if (cookie != null)
rv = cookie["themeName"];
else
{
cookie = new HttpCookie("userTheme");
rv = "Blue";
}
}
cookie.Expires = DateTime.Now.AddYears(100);
cookie["themeName"] = rv;
HttpContext.Current.Response.SetCookie(cookie);
return rv;
}
}
Hope I helped somebody. If you'd rather do it all in jQuery here's Tim Vanfosson's Theme Manager jQuery Plugin
Cheers,
.pd.
I have asp.net's .aspx page.
that have GridView let say GridViewParent and Each row have the another GridView as GridViewChild. Now GridViewChild have button AddRow and another controls like DropDownControl,RadioButtons..etc... I want after click the button AddRow there must add row on client side. How can i do same. Please guide me .... Send me code
<script type="text/javascript" src="../../js/jquery-1.3.2.min.js"></script>
<script language="javascript" type="text/javascript">
$(document).ready(function() {
$('#<%=cmdAdd.ClientID %>').bind('click', function(event) {
//debugger;
event.preventDefault();
var $grid = $('#<%=ctlGrid.ClientID %> ');
var $row = $grid.find('tr:last').clone().appendTo($grid);
$row.find('select')[0].selectedIndex = 0;
$row.find('input').each(function() {
$(this).val("");
});
return true;
});
});