I'm working on an ASP.Net C# Google Charts internal reporting site but am having trouble getting the chart to display. Code seems to run fine and allows me to run in debug.
I can get to the ASP page, but there is no chart present.
EDIT: Initial issue was down to misplaced ], how silly of me!
I'm now faced with the following in the Browser Console, can any help?
A Parser-blocking, cross site (i.e. different eTLD+1) script,
https://www.google.com/uds/?file=visualization&v=1&packages=corechart,
is invoked via document.write. The network request for this script MAY
be blocked by the browser in this or a future page load due to poor
network connectivity. If blocked in this page load, it will be
confirmed in a subsequent console message.See
https://www.chromestatus.com/feature/5718547946799104 for more details
.
Code below;
ASP Page:
<%# Page Title="" Language="C#" MasterPageFile="~/Site.Master"
AutoEventWireup="true" CodeBehind="ADMReports.aspx.cs"
Inherits="ADMReports.ADMReports" %>
<%# Register Assembly="ADMReports" Namespace="ADMReports" TagPrefix="asp" %>
<asp:Content ID="Content1" ContentPlaceHolderID="MainContent" runat="server">
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="https://www.google.com/jsapi"></script>
</head>
<body>
<div id="b_sale" style="width:500px; height:300px;">
TEST
</div>
</body>
<script>
// VISUALIZATION API.
google.load("visualization", "1", { packages: ["corechart"] });
google.setOnLoadCallback(createPIE);
function createPIE() {
// SET CHART OPTIONS.
var options = {
title: 'Total Invoices Per Month',
colors: ['#888', 'orange'],
is3D: true
};
$.ajax({
url: "ADMReports.aspx",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
success: function (data) {
var arrValues = [['Year', 'Month', 'OrdersProcessed']]; // DEFINE AN ARRAY.
var iCnt = 0;
$.each(data.d, function () {
// POPULATE ARRAY WITH THE EXTRACTED DATA.
arrValues.push([data.d[iCnt].Year, data.d[iCnt].Month], data.d[iCnt].OrdersProcessed]);
iCnt += 1;
});
var figures = google.visualization.arrayToDataTable(arrValues)
var chart = new google.visualization.PieChart(document.getElementById('b_sale'));
chart.draw(figures, options);
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert('Got an Error');
}
});
}
</script>
</html>
Code behind asp page
I will be amending the SQL query to pull from a Stored Procedure, but kept it simple for testing purposes.
public partial class ADMReports : System.Web.UI.Page
{
private string Year;
private string Month;
private int OrdersProcessed;
protected void Page_Load(object sender, EventArgs e)
{
}
[WebMethod]
public List<ADMReports> Total_Invoices()
{
List<ADMReports> Invoices = new List<ADMReports>();
string sConnString = "Data Source=<servername>;Initial Catalog=<DB>;Integrated Security=True";
SqlConnection myConn = new SqlConnection(sConnString);
SqlCommand objComm = new SqlCommand("SELECT YEAR(DateTimeScanned) AS Year, MONTH(DateTimeScanned) AS Month, COUNT(OrderNumber) AS OrdersProcessed FROM tabTrace WHERE YEAR(DateTimeScanned) = YEAR(GETDATE()) GROUP BY MONTH(DateTimeScanned), YEAR(DateTimeScanned) ORDER BY MONTH ASC ", myConn);
myConn.Open();
SqlDataReader sdr = objComm.ExecuteReader();
while (sdr.Read())
{
ADMReports objValues = new ADMReports();
objValues.Year = sdr["Year"].ToString();
objValues.Month = sdr["Month"].ToString();
objValues.OrdersProcessed = (int)sdr["OrdersProcessed"];
Invoices.Add(objValues);
}
myConn.Close();
sdr.Close();
return Invoices;
}
}
I would strongly recommend to add all related scripts in local project and remove links to third-party references eg. google in this case. This will help in reducing load time for page also you will not be surprised with random updates of such scripts which are hosted on other server.
Related
I have a problem with ajax
This is the code:
$(document).ready(function () {
show_page(1);
});
function show_page(page) {
debugger;
$.ajax({
type: 'post',
url: 'OrdiniServer.aspx',
data: {
page: page
},
success: function (response) {
$("#table_ordini").html(response);
}
});
return false;
}
This function is included inside RistoratoreAccount.aspx which itself, is located inside a masterpage.
So when I start this function, it should call the page "OrdiniServer.aspx", but the browser console gives me this error:
jquery-1.3.2.min.js:8 POST http://localhost:10343/OrdiniServer.aspx 500 (Internal Server Error)
send # jquery-1.3.2.min.js:8
ajax # jquery-1.3.2.min.js:8
show_page # RistoratoreAccount.aspx:440
(anonymous function) # RistoratoreAccount.aspx:433
j # jquery-1.3.2.min.js:3
fireWith # jquery-1.3.2.min.js:3
ready # jquery-1.3.2.min.js:3
J # jquery-1.3.2.min.js:3
I tried to set the OrdiniServer.aspx with ContentPlaceHolder and without it but it still doesn't work.
I tried to use breakpoint on the codebehind but it doesn't start, so the error is not in the code...
So this is the OrdiniServer.aspx page:
<%# Page Language="C#" AutoEventWireup="true" MasterPageFile="~/MasterBack.Master" CodeBehind="OrdiniServer.aspx.cs" Inherits="FoodDelivery.OrdiniServer" %>
<asp:Content ID="cp2" ContentPlaceHolderID="ContentPlaceHolder2" runat="server">
</asp:Content>
p.s. I tried this code with another project that doesn't have masterpage and it works...
use get method instead of post try below code
$(document).ready(function () {
show_page(1);
});
function show_page(page) {
debugger;
$.get("/OrdiniServer.aspx", { page: page }, function (data) {
$("#table_ordini").html(data.toString());
})
}
try this .
I want to create a tagging system for my website which allows user to enter the required skills,separated by comma, using ASP.net and C#.
In detail:
A textbox will receive tags, separated by comma.
Suggestions will be provided while typing, based on AVAILABLE tags in my database.
Suggested tags will be displayed, below the textbox.
If a new tag is encountered, it is inserted into database.
The tags (separated by comma), given by the user could be further manipulated according to my needs (a way of doing that).
I want to make a separate entry for each and every tag into the database.
I tried using Tag-it by Levy Carneiro Jr.. it is working perfect for local source.
But when I tried attaching it with my database using this. It just doesn't work.
My code:-
<script type="text/javascript">
$(document).ready(function () {
SearchText();
});
function SearchText() {
$(".autosuggest").autocomplete({
source: function (request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "tag.aspx/GetAutoCompleteData",
data: "{'username':'" + document.getElementById('singleFieldTags2').value + "'}",
dataType: "json",
success: function (data) {
response(data.d);
},
error: function (result) {
alert("Error");
}
});
}
});
}
<script>
$(function () {
//Local sample- //var sampleTags = ['c++', 'java', 'php', 'coldfusion', 'javascript', 'asp', 'ruby', 'python', 'c', 'scala', 'groovy', 'haskell', 'perl', 'erlang', 'apl', 'cobol', 'go', 'lua'];
$('#singleFieldTags2').tagit({
});
});
</script>
<body>
<form id="form1" runat="server">
<asp:TextBox name="tags" id="singleFieldTags2" value="Apple, Orange" class="autosuggest" runat="server"></asp:TextBox>
</form>
Backend C# code-
[WebMethod]
public static List<string> GetAutoCompleteData(string username)
{
List<string> result = new List<string>();
using (SqlConnection con = new SqlConnection("Data Source=ZESTER-PC;Initial Catalog=mystp;Integrated Security=True"))
{
using (SqlCommand cmd = new SqlCommand("select tag_name from tags where tag_name LIKE '%'+#SearchText+'%'", con))
{
con.Open();
cmd.Parameters.AddWithValue("#SearchText", username);
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
result.Add(dr["tag_name"].ToString());
}
return result;
}
}
}
Here tags is my tag table containing tag_id and tag_name.
I have created the Tagging System using ASP.net
Check it out.. nd do rate it..
Tagging System using ASP.net by Sumanyu Soniwal
I am developing a web application using asp.net c# and using MS SQL as database. In my application I want to plot a graph of mothly sales. For doing that I found very nice jquery plugin called flot.
But the problem is that I dont know how to pass my sql data to flot. I've a table which has two columns date (DateTime) and number of sales (int). I want the number of sales on y axis and date on x axis.
I googled alot around the web, but I didn't find much help about how to pass MS SQL data to flot.
Please any one can help me to do so.
Thanks in advance.
here is demo code
in code behind
public class chartdata
{
public string Date { get; set; }
public int Sales { get; set; }
}
[System.Web.Services.WebMethod]//public static web method in code behind
public static List<chartdata> GetData() //int StartRowindex,
{
List<chartdata> myResult= new List<chartdata>();
using (SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["demo"].ConnectionString))
{
//string sqlString = "SelectbyYearTotalProductAssign";
string sqlString = "SelectbyYearTotalProductAssign1";
using (SqlCommand cmd = new SqlCommand(sqlString, conn))
{
cmd.CommandType = System.Data.CommandType.StoredProcedure;
conn.Open();
SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
while (rdr.Read())
{
chartdata obj = new chartdata();
obj.Sales = Convert.ToInt32(rdr["Sales"]);
obj.Date = rdr["Date"].ToString();
myResult.Add(obj);
}
conn.Close();
}
}
return myResult;
}
your html
<div id="chart1"></div>
<script language="javascript" type="text/javascript">
jQuery(document).ready(function () {
DrowChart();
});
function DrowChart() {
jQuery("#chart1").html('');
var list12 = [];
jQuery.ajax({
type: "POST",
url: "Default.aspx/GetData",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: false,
data: "{}",
success: function (data) {
jQuery.map(data.d, function (item) {
var list = [];
list.push("'" + item.Date + "'");
list.push(item.Sales);
list12.push(list);
});
var plot1 = jQuery.jqplot('chart1', [list12],
{
seriesDefaults: {
// Make this a pie chart.
renderer: jQuery.jqplot.PieRenderer,
rendererOptions: {
// Put data labels on the pie slices.
// By default, labels show the percentage of the slice.
showDataLabels: true
}
},
legend: { show: true, location: 'e' }
}
);
}
});
}
</script>
<script type="text/javascript" src="chartLib/jquery.jqplot.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.barRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.pieRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.categoryAxisRenderer.min.js"></script>
<script type="text/javascript" src="chartLib/plugins/jqplot.pointLabels.min.js"></script>
<link rel="stylesheet" type="text/css" href="chartLib/jquery.jqplot.min.css" />
You could use a jQuery Ajax call to get your flot data from server-side in JSON format. If successful then parse the JSON object and call $.plot using your placeholder div, the parsed JSON result, and any options.
i need to use JavaScript on my website. When i create new web page,which is properly work with JavaScript. When i create a new web page, which is child page, derived from master page. this page does not support my JavaScript. I use this code for auto-complete property for multiple words.
My code is here:
JavaScript code in content place holder in header
<%# Page Language="C#" MasterPageFile="~/Master_Front.master" AutoEventWireup="true"
CodeFile="Mailbox.aspx.cs" Inherits="Mailbox" Title="Mail System" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
<link href="Style/ui-lightness/jquery-ui-1.8.21.custom.css"rel="stylesheet" type="text/css" />
<script src="script/jquery.min.js" type="text/javascript"></script>
<script src="script/jquery-ui.min.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
SearchText();
});
function SearchText() {
$("#txtto").autocomplete({
source: function(request, response) {
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
url: "Mailbox.aspx/GetAutoCompleteData",
data: "{'username':'" + extractLast(request.term) + "'}",
dataType: "json",
success: function(data) {
response(data.d);
},
error: function(result) {
alert("Error");
}
});
},
focus: function() {
// prevent value inserted on focus
return false;
},
select: function(event, ui) {
var terms = split(this.value);
// remove the current input
terms.pop();
// add the selected item
terms.push(ui.item.value);
// add placeholder to get the comma-and-space at the end
terms.push("");
this.value = terms.join(", ");
return false;
}
});
$("#txtto").bind("keydown", function(event) {
if (event.keyCode === $.ui.keyCode.TAB &&
$(this).data("autocomplete").menu.active) {
event.preventDefault();
}
})
function split(val) {
return val.split(/,\s*/);
}
function extractLast(term) {
return split(term).pop();
}
}
</script>
</asp:Content>
C# code:
[WebMethod]
public static List<string> GetAutoCompleteData(string user_name)
{
List<string> result = new List<string>();
SqlDataReader dr=General.ReturnDR("select DISTINCT mailid from UserDetails where mailid LIKE '%"+user_name+"%'");
while (dr.Read())
{
result.Add(dr["mailid"].ToString());
}
return result;
}
You can put all script in document.ready so that the elements are ready when script acces them.
$(document).ready(function(){
//put all your script of child page here.
});
I have a form that is going to be executing a failry long running process. Not just long, but many small steps during an install process. I'm trying to stay away from using the built in MS AJAX as much as possible in my entire application, but will use it on this page if it's just the easier way to do things.
But what I want is to only one jQuery AJAX call to code behind and have code behind spit out progess as it hits each step. Here is what I've gotten so far. It's just sample code but it's what I'm trying to do.
UI:
<head runat="server">
<title></title>
<script type="text/javascript">
$(function() {
$(this).find("#submitForm").click(function() {
RunCodeBehind();
});
});
function RunCodeBehind() {
$.ajax({
error: function(msg) { alert(msg) },
type: "POST",
url: 'Other.aspx/RunLongRunningProcess',
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(responses) {
if (responses.d != "") {
//Display process in UI
var divEvents = document.getElementById("events");
divEvents.innerText = divEvents.innerText + "\n" + data;
}
else {
//no response, update as failed
var divEvents = document.getElementById("events");
divEvents.innerText = divEvents.innerText + "No response from code behind";
}
}
});
}
</script>
</head>
<body>
<form id="form1" runat="server">
<div>
<a id="submitForm">Start Process</a>
<br />
<div id="events"></div>
</div>
</form>
</body>
Code behind:
[WebMethod]
public static string RunLongRunningProcess()
{
string returnValue;
var sqlQuery = "SELECT COUNT(*) FROM Users;"; //generic sql query
returnValue = ExecuteQuery(sqlQuery);
//feedback cout total to UI, continue process
var sqlQueryInsert = #"INSERT INTO Log (UserCount)
SELECT COUNT(*) FROM Users;"; //generic sql insert
returnValue = ExecuteNonQuery(sqlQueryInsert);
//feedback insert step to UI
var sqlQuery = "SELECT user + ' - ' + name + ' - ' + favday FROM Users;"; //generic sql query
returnValue = ExecuteQuery(sqlQuery);
//feedback selection to UI
return returnValue;
}
Any pointers on how to make it feed back to the UI more than once with just a single call?
I would be inclined to try the other way around, and poll another web service method from your JQuery code instead.
In your 'RunLongRunningProcess' method, I would simply update a session integer variable with values from 0 to 100.
Then I would create a separate web service method that returns the current value of this variable.
You can then poll this new method every (for example) second to get the current upload status.
I believe PeriodicalUpdater for JQuery will allow you to achieve this:
http://www.360innovate.co.uk/blog/2009/03/periodicalupdater-for-jquery/