I have a data table containing data from a SQL database. I want to plot this data on a chart.js bubble chart. I have so far done the following: 1. Queried the SQL database and retrieved the output into an objectList of type BubbleData
which contains two properties:
public string category { get; set; }
public decimal score { get; set; }
[System.Web.Services.WebMethod]
public static List<BubbleData> ReturnData()
{
string connectionstring = ConfigurationManager.ConnectionStrings["SQLConString"].ConnectionString;
SqlConnection cn = new SqlConnection(connectionstring);
cn.Open();
SqlCommand cmd = new SqlCommand("dbo.sp_ui_ExecView_Bubble", cn);
cmd.Parameters.AddWithValue("@RunID", 1);
var da = new SqlDataAdapter(cmd);
cmd.CommandType = CommandType.StoredProcedure;
var dt = new DataTable();
da.Fill(dt);
cn.Close();
List<BubbleData> objectList = new List<BubbleData>();
foreach (DataRow dr in dt.Rows)
{
objectList.Add(new BubbleData()
{
category = dr["Category"].ToString(),
score = Convert.ToDecimal(dr["Score"].ToString()) * 100
});
}
return objectList;
}
$(function() {
var popData = [];
$.ajax({
type: "POST",
async: false,
url: "ExecView.aspx/ReturnData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var myData = data.d;
console.log(myData[0]);
}
});
var popData = {
datasets: [{
label: ['Test'],
data: [{
x: 100,
y: 0
}, {
x: 60,
y: 30
}, {
x: 40,
y: 60
}, {
x: 80,
y: 80
}, {
x: 20,
y: 30
}, {
x: 0,
y: 10
}],
}]
};
var bubbleOptions = {
responsive: true,
legend: {
display: false
},
};
var ctx5 = document.getElementById("bubble_chart").getContext("2d");
new Chart(ctx5, { type: 'bubble', data: popData, options: bubbleOptions });
});
In the javascript file I have the data eg myData[0] but how do I use it dynamically in the popData variable. The values hardcoded in data (popData) I want to replace with the values from the ajax request WebMethod.
I would do something like this:
$(function() {
var bubbleData;
$.ajax({
type: "POST",
async: false,
url: "ExecView.aspx/ReturnData",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
var bubbleDatas = data.d;
bubbleData = new Array(bubbleDatas.length);
for (i = 0; i < bubbleDatas.length; i++) {
bubbleData[i] = {x: i, y:bubbleDatas[i].score};
}
}
});
var popData = {
datasets: [{
label: ['Test'],
data: bubbleData
}]
};
var bubbleOptions = {
responsive: true,
legend: {
display: false
},
};
var ctx5 = document.getElementById("bubble_chart").getContext("2d");
new Chart(ctx5, { type: 'bubble', data: popData, options: bubbleOptions });
});
I did not test this code and i'm not a javascript expert, so take this as a suggestion rather than a sure answer.
I hope I was helpful
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.