Script codes:
<script type="text/javascript">
function drawVisualization01(dataValues) {
var data = new google.visualization.DataTable();
data.addColumn('string', 'Column Name');
data.addColumn('number', 'Class Average ');
data.addColumn('number', 'Score ');
for (var i = 0; i < dataValues.length; i++) {
data.addRow([dataValues[i].ColumnName, dataValues[i].Value1, dataValues[i].Value2]);
}
var options = {
title: 'Topics Performance',
hAxis: { title: 'Topics', titleTextStyle: { color: 'red', fontSize: 15 }, textStyle: { fontSize: 12} },
vAxis: { format: '###.##%', textStyle: { fontSize: 12 }, maxValue: 1, minValue: 0 }
};
var formatter = new google.visualization.NumberFormat({ pattern: '###.##%' });
formatter.format(data, 1);
formatter.format(data, 2);
var chart_div01 = document.getElementById('visualization1');
var chart = new google.visualization.ColumnChart(chart_div01);
// Wait for the chart to finish drawing before calling the getImageURI() method.
google.visualization.events.addListener(chart, 'ready', function () {
chart_div01.innerHTML = '<img src="' + chart.getImageURI() + '">';
console.log(chart_div01.innerHTML);
var result = Foo(document.getElementById('<%=Textbox1.ClientID%>').value);
document.getElementById('<%=Textbox2.ClientID%>').value = chart.getImageURI();
});
chart.draw(data, options);
}
</script>
**JSON function**
<script >
function Foo(user_id) {
// Grab the information
var values = user_id;
var theIds = JSON.stringify(values);
// Make the ajax call
$.ajax({
type: "POST",
url: "ProgressReportNew.aspx/Done", // the method we are calling
contentType: "application/json; charset=utf-8",
data: {ids: theIds },
dataType: "json",
success: function (result) {
alert('Yay! It worked!');
},
error: function (result) {
alert('Oh no :(');
}
});
}
</script>
[WebMethod]
public static void done(string ids)
{
String a = ids;
HttpContext context = HttpContext.Current;
context.Session["a"] = a;
}
C# code:
int t1 = Textbox1.Text.Trim().Length;
string as1 = (string)(Session["a"]);
Its brief code, I want convert the google chart to image in one click. Its my code ;from server side I want to pass the image base64 string, but unfortunately I am not getting into the text box; I tried using Ajax still it is not happening.
Can anyone help me to resolve this problem, before I used 2 button first to convert image and pdf it worked, but one button its not working.
Related
I'm trying to use select2 multiselect with an ajax call to retrieve the data and filter based on user input, but when it hits the controller the params are null. Unfortunately (I think because it's custom select2 api) I can't put a chrome breakpoint in the ajax call to mess with it, but the URL looks fine on the network tab. Right now the ajax calls are written slightly differently, bc I've been trying different solutions; neither work.
I also tried this post, which he said worked, but no dice for me:
jquery-select2 always sends null params in controller
$(".filter-agencies").select2({
//data: agencies,
ajax: {
cache: false,
datatype: 'JSON',
type: 'GET',
url: 'Home/GetFilterAgency',
data: function (params) {
return {q:params}
},
processResults: function (data) {
return {
results: data
}
}
},
placeholder: 'Agencies',
width: '150',
multiple: true,
closeOnSelect: false,
minimumInputLength: 4
////tags: true
});
$(".filter-advertisers").select2({
//data: filterSelect,
ajax: {
url: 'Home/GetFilterAdvertiser',
data: function (params) {
var query = {
search: params.term
}
return query
},
processResults: function (data) {
//advertisers = $.map(data, function (obj) {
// obj = { id: i, text: obj }
// i = i + 1;
// return obj
//})
return {
results: data
}
}
},
placeholder: 'Advertisers',
closeOnSelect: false,
minimumInputLength: 4,
allowClear: true,
width: '150',
multiple: true
});
[HttpGet]
public string GetFilterAdvertiser(string query)
{
var x = _orderedLinesProcessor.GetFilterAdvertiser();
var i = 0;
var dict = new Dictionary<int, string>();
foreach (var el in x)
{
dict.Add(i, el);
i += 1;
}
return JsonConvert.SerializeObject(dict);
}
Change query to search in controller:
public string GetFilterAdvertiser(string search)
I am working with ASP.NET MVC 5, jquery and the datatables plugin in a project. My goal is to use the serverside function of datatables in order to retrieve data of a database and then to display the dat in a datatable. This works fine in one part of my code. Here you can see the jquery code where I use the datatables plugin:
var problemTable = $('#ProblemTable').DataTable({
processing: true, // show message while querying fro data
serverSide: true,
ajax: {
url: "/OverView/LoadProblems"
}
});
As you can see in the following picture, the request is successful and my datatables gets filled as it should in the website.
The request URL looks like this:
So far is everything fine. But now comes the part, which is driving me crazy. In a different jquery script I try to call again the the datatables method for a new datatable. The code looks like this:
$('.DeleteEntity').click(
function () {
try
{
var deleteTable = $('#DeleteTable').DataTable({
processing: true,
serverside: true,
destroy: true,
ajax: {
url: "/Administration/ShowEntriesDelete"
}
});
}
catch (e)
{
console.log(e);
}
});
This Ajax call doesnt work anymore. As you can see the following picture, the action method in C# Code fails.
In this case, the request URL looks like this.
So here is my question: Why do I get this behavior although I use the same function in my jquery code? Or is there something which I got totally wrong?
I think that I have tried everything by now, but I still don´t get it. Both datatables look exact the same in HTML, only id and column headers are different.
I also looked for similar questions, but I couldn't find anything. I would be very glad if someone could give me a hint for this.
Best regards!
EDIT:
#Calvin Ananda
I adapted your answer and added both DataTable functions to one script, just for testing purpose. Here is the hole script.
var troubleshootingIDs = [];
$(document).ready(
function () {
// if I call this method, everything works just fine, the c# code throws an error (which it should) but the ajax method is successfull
var problemTable = $('#ProblemTable').DataTable({
processing: true, // show message while querying fro data
serverSide: true,
"ajax": "/Administration/ShowEntriesDelete"
});
// if I call this method, the ajax method doesnt get called, because there is absolute no data provided in the url
var deleteTable = $('#DeleteTable').DataTable({
processing: true,
serverside: true,
destroy: true,
"ajax": "/Administration/ShowEntriesDelete",
"columns": [
{ "data": "Description" },
{ "data": "Connection" },
{ "data": "Action" }
]
});
var table = $('#reasonTable').DataTable({
pageLength: 2,
lengthChange: false,
columnDefs: [
{
targets: [3],
className: "hide_me"
}
]
}
);
var agentButton = $('.agentButton');
$('td').on('click', '#BadgeContainer', function () {
var IDs = [];
$('#DocList').empty();
$('.DocLinkID').each(function (counter) {
IDs[counter] = $(this).html();
});
console.log(IDs);
$.ajax({
url: "/OverView/GetDocuments",
traditional: true,
data: { IDs: IDs },
content: 'application/json; charset=utf-8',
success: listDocuments
});
});
$('#reasonTable tbody').on('click', 'tr', function () {
$('#SolutionList').empty();
troubleshootingIDs = [];
if ($(this).hasClass('selected')) {
}
else {
table.$('tr.selected').removeClass('selected');
$(this).addClass('selected');
}
var selectedReason = $('.ReasonGuid', this).text();
$.ajax({
url: '/OverView/ReasonJson',
contentType: 'application/json; charset=utf-8',
data: { 'selectedReason': selectedReason },
success: handleJsonForWizard
}
);
}
);
$('.SolutionButton').on('click',
function () {
var indexToRemove = [];
var dummyArray = [];
for (var counter = 0; counter < troubleshootingIDs.length; counter++) {
if ($('#q' + (+counter * 2)).hasClass('btn-active')) {
indexToRemove.push(counter);
}
dummyArray[counter] = troubleshootingIDs[counter];
}
for (var counter = indexToRemove.length - 1; counter >= 0; counter--) {
dummyArray.splice(indexToRemove[counter], 1);
}
$.ajax(
{
url: '/OverView/GetSolutions',
contentType: 'application/json; charset=utf-8',
traditional: true,
data: { troubleshootingIDs: dummyArray },
success: function (json) {
$('#SolutionList').empty();
try {
for (var counter = 0; counter < Object.keys(json).length; counter++) {
$('#SolutionList').append('<li class="list-group-item">' + json[counter] + '</li>');
}
}
catch (err) {
}
}
}
);
}
);
$('#ProblemTable tbody').on('click', '.WizardButton',
function () {
var IdToGet = $(this).attr('id');
var url = '/OverView/Wizard?SelectedID=';
window.location.replace(url + IdToGet);
}
);
// Carousel fuction overriding (doesn't work wiht jquery template)
$('.carousel-control.left').click(
function () {
var parentId = '#' + $(this).parent().attr('id');
$(parentId).carousel('prev');
}
);
$('.carousel-control.right').click(
function () {
var parentId = '#' + $(this).parent().attr('id');
$(parentId).carousel('next');
}
);
// comment to define
$('.row #BackToTable').click(
function () {
window.location.replace("/OverView");
}
);
$('body').on('click', '.AgentButton',
function () {
var idNum = $(this).attr('id');
var num = idNum.substring(1);
$('#' + idNum).toggleClass('btn-active');
if ((num % 2) == 0) {
var numToCompare = +num + 1;
var classToCompare = $('#q' + numToCompare).attr('class');
if (classToCompare == 'btn AgentButton btn-active') {
$('#q' + numToCompare).toggleClass('btn-active');
}
}
else {
var numToCompare = +num - 1;
var classToCompare = $('#q' + numToCompare).attr('class');
if (classToCompare == 'btn AgentButton btn-active') {
$('#q' + numToCompare).toggleClass('btn-active');
}
}
}
);
function handleJsonForWizard(json) {
initializeCarousel(json.ImgLinks);
initializeAgent(json.Troubleshootings, json.TroubleshootingIDs);
}
function initializeCarousel(imgLinks) {
$('#ReasonVisualisation > ol').empty();
$('#ReasonVisualisation > .carousel-inner').empty();
for (var counter = 0; counter < Object.keys(imgLinks).length; counter++) {
$('#ReasonVisualisation > ol').append('<li data-target="#ReasonVisualisation" data-slide-to="' + counter + '"></li>');
$('#ReasonVisualisation > .carousel-inner').append('<div class="item"><img src="' + imgLinks[counter] + '"/> </div>');
}
$('#ReasonVisualisation > ol >li:first').addClass('active');
$('#ReasonVisualisation > .carousel-inner>div:first').addClass('active');
var list = $('#ReasonVisualisation > ol').html();
var inner = $('#ReasonVisualisation > .carousel-inner').html();
}
function initializeAgent(troubleshootings, ids) {
$('#Agent').empty();
for (var counter = 0; counter < Object.keys(troubleshootings).length; counter++) {
$('#Agent').append('<div>' + troubleshootings[counter] + ' </div>');
$('#Agent').append('<div class="btn AgentButton" id="q' + (counter * 2) + '">Yes</div>');
$('#Agent').append('<div class="btn AgentButton" id="q' + ((counter * 2) + 1) + '">No</div>');
agentButton = $('.AgentButton');
troubleshootingIDs[counter] = ids[counter];
}
}
function listDocuments(json) {
//Array.isArray(json);
if (json.length > 1) {
for (var counter = 0; counter < json.length; counter++) {
$('#DocList').append('<li> <a href=\"' + json[counter] + '\" > Link </a></li>');
}
}
}
}
);
The most interesting part are the first to methods within the script. In my provided code within the code I described my issue. I simply don´t why ajax reacts so different...
I use this method in my project, and it works.
But I dont know if it works to answer your problem.
JSFiddle Here
Change to "ajax": "/OverView/LoadProblems"
var problemTable = $("#ProblemTable").DataTable({
processing: true, // show message while querying fro data
serverSide: true,
"ajax": "/OverView/LoadProblems"
});
=========================================================================
$(".DeleteEntity").click(
function () {
try
{
var deleteTable = $("#DeleteTable").DataTable({
processing: true,
serverside: true,
destroy: true,
"ajax": "/Administration/ShowEntriesDelete"
});
}
catch (e)
{
console.log(e);
}
});
I'm trying to use AJAX and calling web method like this in my code.
function generate_source(year_source, month_source) {
var gData_source = '';
if (year_source) {
gData_source = [];
gData_source[0] = year_source;
gData_source[1] = month_source;
console.log('first part');
}
else {
var d_source = new Date();
gData_source = [];
gData_source[0] = d_source.getFullYear();
gData_source[1] = d_source.getMonth() + 1;
console.log('second part');
}
var jsonData_source = JSON.stringify({
gData_source: gData_source
});
var ctx = document.getElementById("order_source").getContext('2d');
$.ajax({
url: "dashboard.aspx/getordersource",
data: jsonData_source,
type: "POST",
contentType: "application/json; charset=utf-8",
dataType: "json",
beforeSend: function () {
$("#loader_divsource").show();
},
success: function (response) {
$("#loader_divsource").hide();
var chartLabel = eval(response.d[0]); //Labels
var chartData = eval(response.d[1]); //Data
var myChart = new Chart(ctx, {
type: 'doughnut',
data: {
labels: chartLabel,
datasets: [
{
type: 'doughnut',
label: chartLabel,
data: chartData,
backgroundColor: [
"#FF6384",
"#36A2EB",
],
hoverBackgroundColor: [
"#FF6384",
"#36A2EB",
]
}
]
}
});
}
});
}
var d_source = new Date();
gData_source = [];
$('#year_source').val(d.getFullYear());
$('#month_source').val(d.getMonth() + 1);
generate_source('', '');
My web method is like this;
[System.Web.Services.WebMethod]
public static List<string> getordersource(List<int> gData)
{
DataSet ds = ws_db.get_Dataset_order_source();
var returnData = new List<string>();
......
return returnData;
}
Whenever I try to run this data, my breakpoint for the web method is not hit. Further, if i use the same method without data, i don't get this error. It's driving me crazy.
I think your problem is in this code :
var jsonData_source = JSON.stringify({
gData_source: gData_source
});
you are trying to serialize array with key value pair that it is become invalid.
change to this :
var jsonData_source = JSON.stringify(gData_source);
also your web method should be like this :
[System.Web.Services.WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.JSON)]
// just return a string, not list, your JSON string should have contain all your enumerable in your string Data
public static string getordersource(List<int> gData)
{
DataSet ds = ws_db.get_Dataset_order_source();
JsonSerializer serializer = new JsonSerializer();
var returnData = serializer.serialize(ds);
......
return returnData;
}
Hope it helps.
I can generate a Pie Chart Just like the picture by using the code below
<script>
var pieChartData = [
{ label: "Data 1", data: 16, color: "#62cb31", },
{ label: "Data 2", data: 6, color: "#A4E585", },
{ label: "Data 3", data: 22, color: "#368410", },
{ label: "Data 4", data: 32, color: "#8DE563", }
];
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
</script>
Now what I want to do is to generate the var data = [] dynamically from Controller. How to do this? Also the data is from the Database.
By Combining Pranav Patel and Ghanshyam Singh answers
I was able able to reach the desired output
Model
public class GenderPieChart_Model
{
public string GenderDesc { get; set; }
public int GenderID { get; set; }
}
Controller
public JsonResult Gender()
{
Dashboard_Layer data = new Dashboard_Layer();
var lst = data.Gender();
return Json(lst, JsonRequestBehavior.AllowGet);
}
Business Layer
public IEnumerable<GenderPieChart_Model> Gender()
{
List<GenderPieChart_Model> data = new List<GenderPieChart_Model>();
using (SqlConnection con = new SqlConnection(Connection.MyConn()))
{
SqlCommand com = new SqlCommand("dbo.sp_Project_DashBoard 4", con);
con.Open();
SqlDataReader reader = com.ExecuteReader();
while (reader.Read())
{
GenderPieChart_Model value = new GenderPieChart_Model();
value.GenderDesc = Convert.ToString(reader.GetValue(0));
value.GenderID = Convert.ToInt32(reader.GetValue(1));
data.Add(value);
}
}
return data;
}
View
<div class="flot-chart-content" id="_ByGender" style="height: 150px"></div>
<script>
$(document).ready(function () {
$.ajax({
type: "POST",
url: "#Url.Action("Gender", "Dashboard")",
content: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = data;
var pieChartData = [];
$.each(data, function (i,v) {
pieChartData.push({ label: v.GenderDesc, data: v.GenderID, color: "#62cb31", });
})
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByGender"), pieChartData, pieChartOptions);
}
})
});
</script>
you can call when your controller on ready event and after getting data (returned Json from your controller) can process further. You can try like below
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "<YOUR URL>",
data: "<YOUR PARAMETER IF NEEDED>",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function(data){ //data is your json returned from controller
var myData = JSON.parse(data);
//create your 'pieChartData' from object 'myData'
//pieChartData =
var pieChartOptions = {
series: {
pie: {
show: true
}
},
grid: {
hoverable: true
},
tooltip: true,
tooltipOpts: {
content: "%p.0%, %s", // show percentages, rounding to 2 decimal places
shifts: {
x: 20,
y: 0
},
defaultTheme: false
}
};
$.plot($("#_ByRegion"), pieChartData, pieChartOptions);
}
});
});
</script>
Its simple just return Json from your controller:
first create a model class for the properties
public class Chart
{
public string label{get;set;}
public string data{get;set;}
public string color{get;set;}
}
MVC action method:-
public JsonResult Chart()
{
List<Chart> chartList=new List();
// Code to fetch Data in List chartList
return Json(chartList,JsonRequestBehaviour.AllowGet);
}
Ajax Call:-
<script>
$(document).ready(function(){
$.ajax({
type: "POST", //GET or POST
url: "/Controller/Chart",
data: "<YOUR PARAMETER IF NEEDED>",
dataType: "json",
success: function(data){
$.each(data,function(i,index){
// Code to plot Chart here
});
}
});
});
</script>
I am using chart.js to query sql server and display data on the chart. I have time interval on x-axis and on y-axis i have float data. chart is displaying nice but time interval is displaying continiously. I want time scale to be 30 minute interval and float to be 10.
<script type="text/javascript">
$(document).ready(function () {
$("#btn_line_chart").on('click', function () {
var mb_one = $("#ddl_one").val() + " " + $("#ddl_one_time").val();
var mb_two = $("#ddl_two").val() + " " + $("#ddl_two_time").val();
var jsonData = JSON.stringify({
mobileId_one: mb_one,
mobileId_two: mb_two
});
$.ajax({
type: "POST",
url: "sampleservice.asmx/getLineChartData",
data: jsonData,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess_,
error: OnErrorCall_
});
function OnSuccess_(reponse) {
var aData = reponse.d;
var aLabels = aData[0];
var aDatasets1 = aData[1];
var aDatasets2 = aData[2];
var data = {
labels: aLabels,
datasets: [{
label: "My First dataset",
fill:false,
fillColor: "rgba(220,220,220,0.2)",
strokeColor: "rgba(220,220,220,1)",
pointColor: "rgba(220,220,220,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(220,220,220,1)",
backgroundColor: "rgba(75,192,192,0.4)",
borderColor: "rgba(75,192,192,1)",
data: aDatasets1
},
{
label: "My Second dataset",
fill: false,
fillColor: "rgba(151,187,205,0.2)",
strokeColor: "rgba(151,187,205,1)",
pointColor: "rgba(151,187,205,1)",
pointStrokeColor: "#fff",
pointHighlightFill: "#fff",
pointHighlightStroke: "rgba(151,187,205,1)",
backgroundColor: "rgba(255,0,0,0.4)",
borderColor: "rgba(255,0,0,1)",
data: aDatasets2
}]
};
var ctx = $("#myChart").get(0).getContext('2d');
ctx.canvas.height = 300; // setting height of canvas
ctx.canvas.width = 300; // setting width of canvas
// var lineChart = new Chart(ctx).Line(data, {
// bezierCurve: false
// });//bezierCurve: false,
var lineChart = new Chart(ctx, {
type: "line",
data: data
});
}
function OnErrorCall_(repo) {
alert(repo.toString());
alert("Woops something went wrong, pls try later !");
}
});
});
// window.onload = function () {
// var ctx = document.getElementById("canvas").getContext("2d");
// window.myLine = new Chart(ctx).Line(lineChartData, {
// scaleOverride: true,
// scaleSteps: 10,
// scaleStepWidth: 50,
// scaleStartValue: 0
// });
// }
</script>