As a bunch of others I have a problem getting my JSON feed events to render in the calendar. The problem is often wrong JSON formating, but this is not the case since I've validated it with JSONlint and hardcoded the JSON feed in Site.Master with positive result.
FireBug is getting the JSON response correctly but it is still not showing up in fullCalendar. I'm out of ideas.
The FireBug response:
[{"id":1,"title":"TESTTITLE","info":"INFOINFOINFO","start":"2012-08-20T12:00:00","end":"2012-08-20T12:00:00","user":1}]
JSON.aspx
public partial class JSON : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
// Get events from db and add to list.
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
Response.Write(json);
Response.End();
}
}
Site.master
<link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
<link href='fullcalendar/fullcalendar.css' rel='stylesheet' type='text/css' />
<script src='jquery/jquery-1.7.1.min.js' type='text/javascript'></script>
<script src='fullcalendar/fullcalendar.js' type='text/javascript' ></script>
<script type="text/javascript">
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: 'JSON.aspx'
})
});
</script>
I've been scanning related questions for days but none of them seems to fix mine...
Try this , you have to have a webmethod in aspx file that fullcalendar can call asynchronously
$(document).ready(function () {
$('#fullcal').fullCalendar({
eventClick: function() {
alert('a day has been clicked!');
},
events: function (start, end, callback) {
$.ajax({
type: "POST", //WebMethods will not allow GET
url: "json.aspx/GetEvents", //url of a webmethod - example below
data: "{'userID':'" + $('#<%= hidUserID.ClientID %>').val() + "'}", //this is what I use to pass who's calendar it is
//completely take out 'data:' line if you don't want to pass to webmethod - Important to also change webmethod to not accept any parameters
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (doc) {
var events = []; //javascript event object created here
var obj = $.parseJSON(doc.d); //.net returns json wrapped in "d"
$(obj.event).each(function () { //yours is obj.calevent
events.push({
title: $(this).attr('title'), //your calevent object has identical parameters 'title', 'start', ect, so this will work
start: $(this).attr('start'), // will be parsed into DateTime object
end: $(this).attr('end'),
id: $(this).attr('id')
});
});
callback(events);
}
});
}
})
then this would be in json.aspx
[WebMethod(EnableSession = true)]
public static string GetEvents(string userID)
{
DataClassesDataContext db = new DataClassesDataContext();
List<calevent> eventList = db.calevents.ToList();
// Select events and return datetime as sortable XML Schema style.
var events = from ev in eventList
select new
{
id = ev.event_id,
title = ev.title,
info = ev.description,
start = ev.event_start.ToString("s"),
end = ev.event_end.ToString("s"),
user = ev.user_id
};
// Serialize to JSON string.
JavaScriptSerializer jss = new JavaScriptSerializer();
String json = jss.Serialize(events);
return json;
}
Related
I have created class method in call GetDatabase() with following code:
public string GetDatabase()
{
var db_holiday = dbObj.RetrieveData("SELECT Holiday_description, Date FROM ServiceReport.dbo.WS_Holidays");
if (db_holiday != null)
{
var holiday_rows = db_holiday.Tables[0].Rows;
List<string> des_holiday = new List<string>();
List<string> des_date = new List<string>();
foreach (DataRow row in holiday_rows)
{
var holiday = row["Holiday_description"].ToString();
var date = row["Date"].ToString();
des_holiday.Add(holiday);
des_date.Add(date);
}
}
I've stored two databases into separated list which is des_holday and des_date.
In ASP.net:
<div class="container col-lg-2 bg-warning ">
<div ID="week_display" class="m-grid-col-center">
</div>
</div>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "Test.aspx/GetDatabase",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: OnSuccess
});
});
</script>
</head>
I'm currently using .ajax() to call back GetDatabase().
My main goal is to display all of my element inside the two list.
I'm stuck right and don't know what to do.
I solved it. When the ajax is running, the success will run the OnSuccess function. By putting
function OnSuccess(data) {
console.log(data.d);
}
Will obtain the data.
I have a static pie-chart created using chartJS and now I want to provide the data and labels from an asp.net webservice(asmx) to show the actual data that comes from the database but I don't know how to do that.
This is the Static Chart Code
<!doctype html>
<html>
<head>
<title>Pie Chart</title>
<script src="../../dist/Chart.min.js"></script>
<script src="../utils.js"></script>
</head>
<body>
<div id="canvas-holder" style="width:40%">
<canvas id="chart-area"></canvas>
</div>
<script>
var config = {
type: 'pie',
data: {
datasets: [{
data: [420,576,812],
backgroundColor: [
"#3e95cd", "#8e5ea2", "#3cba9f"
],
label: 'Labels'
}],
labels: [
'iPhone',
'Windows Phone',
'Samsung'
]
},
options: {
responsive: true
}
};
window.onload = function () {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
</body>
</html>
The Data I want to Show
Phone as Chart Label and Amount as Chart-Data
-------------------------
-Phone - Amount-
-------------------------
-iPhone - 323 -
-Windows-Phone - 210 -
-Samsung - 860 -
-------------------------
The Web Service that fetch the data
[WebMethod]
public void GetTotalPhoneSales()
{
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
List<TotalSales> totalSales = new List<TotalSales>();
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetTotalPhoneSales", con)
{
CommandType = CommandType.StoredProcedure
};
con.Open();
SqlDataReader rdr = cmd.ExecuteReader();
while (rdr.Read())
{
TotalSales PhoneSale = new TotalSales
{
Amount = Convert.ToInt32(rdr["Amount"]),
Phone = rdr["Phone"].ToString()
};
totalSales.Add(PhoneSale);
}
}
JavaScriptSerializer js = new JavaScriptSerializer();
Context.Response.Write(js.Serialize(totalSales));
}
Expected output
You may call the web service method from Jquery Ajax function and return the values.
What you have to change is
1) Change the return type of your web method to string[][](Array of string Arrays:because we need to return two arrays)
2) Call this web method with the help of Jquery ajax function and in the success function assign the data and label options with respective arrays received from the jquery ajax call.
documentation of Jquery ajax function
Finally I solved it like this
<script>
//make an ajax call to the webservice
//then use `chartlabel` as label and `chartData` as Data
var chartLabel= [];
var chartData= [];
$.ajax({
url: 'TestService.asmx/GetTotalPhoneSales',
method: 'post',
dataType: 'json',
success: function (data) {
$(data).each(function (index, item) {
chartLabel.push(item.Phone);
chartData.push(item.Amount);
});
},
error: function (err) {
alert(err);
}
});
var config = {
type: 'pie',
data: {
datasets: [{
data: chartData,
backgroundColor: [
"#3e95cd", "#8e5ea2", "#3cba9f"
],
label: 'Labels'
}],
labels: chartLabel
},
options: {
responsive: true
}
};
window.onload = function () {
var ctx = document.getElementById('chart-area').getContext('2d');
window.myPie = new Chart(ctx, config);
};
</script>
Note: Its better to assign the backgroundColor programmatically, so that when new items are added to the database then those items will not show up with same color on the chart by default.
thanks for the hint #Gagan Deep
I am new to Knockout and I am trying to update my ViewModel from an ajax call. This is what I have right now:
LoanDeductions.js
var deductionLine = function (deductionID, deductionName, amount) {
self = this;
self.deductionID = ko.observable(deductionID);
self.deductionName = ko.observable(deductionName);
self.amount = ko.observable(amount);
};
function LoanDeductions(deductions) {
var self = this;
self.loanDeductions = ko.observableArray(ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
}));
// Operationss
self.removeLine = function (line) { self.loanDeductions.remove(line) };
};
and this is my scripts in my view:
#section scripts
{
<script src="~/Scripts/koModel/LoanDeductions.js"></script>
<script type="text/javascript">
var updateValues = function () {
$.ajax({
'url': '#Url.Action("UpdateDeductionValues","LoanApp")',
'data': { amount: $('.LoanAmount').val() },
'success': function (result) {// update viewmodel scripts here}
});
var viewModel = new LoanDeductions(#Html.Raw(Model.CRefLoansDeductions2.ToJson()));
$(document).ready(function () {
ko.applyBindings(viewModel);
$('.datepicker').datepicker();
$('.LoanAmount').change(function () {
updateValues();
};
});
});
</script>
}
So, in my view, I have a dropdown list with class name "LoanAmount" which when value is changed, it will perform an ajax call, send the selected loanAmount value to the server, recompute the deduction amounts, then the server returns a jsonresult that looks like this:
"[{\"deductionID\":1,\"deductionName\":\"Loan Redemption Fee\",\"amount\":53.10},{\"deductionID\":2,\"deductionName\":\"Document Stamp\",\"amount\":9.00}]"
Now what I wanted to do is use this json data as my new viewModel.
Can anyone show me the way how to do this, please note that I manually mapped my viewmodel and didn't used the ko mapping plugin.
Any help will be greatly appreciated. Thank you, more power!
EDIT (in response to Fabio)
function updateData() {
$.ajax({
url: '#Url.Action("UpdateDeductionValues","LoanApp")',
data: { amount: self.selectedLoanAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
});
}
});
}
Not sure If I understood your problem, but if you want to change model values outside of the class, you need to do something like this:
$(document).ready(function () {
var viewModel = new LoanDeductions(#Html.Raw(Model.CRefLoansDeductions2.ToJson()));
ko.applyBindings(viewModel);
$('.datepicker').datepicker();
function updateValues() {
//do you ajax call
//update the model using viewModel.loanDeductions(newItens);
};
$('.LoanAmount').change(function () {
updateValues();
};
});
EDIT 1 - Just to show how to use knockout without jquery.change
function LoadDeductions() {
//declare you properties
var self = this;
self.loanAmount = ko.observable('initialvalueofloanamount');
self.loanDeductions = ko.observableArray();
//create a function to update you observablearray
function updateData() {
$.ajax({
url: '#Url.Content('yourActionhere')' or '#Url.Action('a', 'b')',
data: { amount: self.loadAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
}
});
}
//everytime that loanAmount changes, update the array
self.loanAmount.subscribe(function () {
updateData();
});
//update values initializing
updateData();
};
$(function() {
ko.applyBindings(new LoadDeductions());
});
Bind the select in the HTML
<select data-bind="value: loanAmount"></select>
EDIT 2 - To your second problem
function updateData() {
$.ajax({
url: '/LoanApp/UpdateDeductionValues', //try to write the url like this
data: { amount: self.selectedLoanAmount() },
success: function (deductions) {
//load your array with ko.utils.arrayMap
self.loanDeductions(ko.utils.arrayMap(deductions, function (deduction) {
return new deductionLine(deduction.deductionID, deduction.deductionName, deduction.amount)
}));
}
});
}
Your success handler should look like this.
function(result){
self.loanDeductions(result);
}
Unless you are trying to append in which case it would be
self.loanDeductions(self.loanDeductions().concat(result));
I'm having a problem with fancytree.
I have an aspx page, with a webmethod on the codebehind.
I was trying to initialize the tree with an ajax call, but for some reason it looks the ajax call isn't getting there.
This is my javascript code to initialize the tree:
<script type="text/javascript">
$(function () {
var DT = $.ui.fancytree;
var tree = "";
$.ui.fancytree.debug("Using fancytree " + $.ui.fancytree.version);
/* Load tree from Ajax JSON
*/
$("#tree2").fancytree({
source: {
url: "tree.aspx/getTreeData"
}
});
});
</script>
and this is my codebehind webmethod:
namespace TreeGen
{
public partial class tree : System.Web.UI.Page
{
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json, XmlSerializeString = false)]
public static List<Curso> getTreeData()
{
JavaScriptSerializer TheSerializer = new JavaScriptSerializer();
CourseSerializer course = new CourseSerializer();
course.children = new List<Curso>()
{
new Curso(){
key = "1",
title = "aaaa",
}
};
List<CourseSerializer> courses = new List<CourseSerializer>() { course };
string TheJson = TheSerializer.Serialize(course.children);
Console.WriteLine(TheJson);
return course.children;
}
}
}
What am i doing wrong?
I tried to make a ajax request to the webmethod and i am able to retrieve the json string.
But when i use the fancytree i can't populate the tree!
Thanks in advance!
Regards!
For anyone interested...
The ajax requests made by fancytree are all "GET" requests by default.
I added the ajax options as shown below, and the issue is now solved.
$('#tree2').fancytree({
ajax: { type: "POST", contentType: "application/json" },
source: {
url: "/tree.aspx/getTreeData"
}
});
Regards!
In my aspx page, i have the js like this :-
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = "{'datakey':'hello'}"
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});
</script>
In the same webpage code behind class file ,i have the webmethod defined like this:-
[WebMethod]
public static string SendFile(string key, string data)
{
return data;
}
For some reason, i am able to get the data in the alert used on the html side. alert(msg); is giving me nothing and i am expecting to get the passed value back. In this case it should be 'Hello'.
I am missing something very small here, please help me out here.
Alter these.
The AJAX Call
$(document).ready(function () {
$("#btnLoad").click(function (evt) {
var dataForAjax = "{'datakey':'hello'}";
$.ajax({
contentType: "application/json",
data: dataForAjax,
type: "POST",
url: 'Test1.aspx/SendFile',
success: function (msg) {
var msg = msg.hasOwnProperty("d") ? msg.d : msg;
alert(msg.datakey);
}
});
evt.preventDefault();
});
});
The WebMethod
[WebMethod]
public static object SendFile(string datakey)
{
return new
{
datakey = datakey
};
}
Hope this helps.
Update:
`evt.preventDefault is for preventing postback in case your control was something like input type="submit" or asp:Button
.d is ASP.NET 3.5+ feature to prevent XSS vulnerability. ( link here )
The return type is object for the web method for automatic serialization ( link here )
Also you could omitdataType in $.ajax call but contentType is an absolute necessity ( link here )
This:
var dataForAjax = "{'datakey':'hello'}"
Should be:
var dataForAjax = {'datakey':'hello'}
AJAX does not (by default anyway) send json - it sends FORM INPUT elements! jQuery is nice and will convert javascript objects into that for you.
If you really need to you can send json, but I really doubt you do, it's rare to do that.
When you send data to method you must send apropriate key-value pairs, using object in Javascript.
Examle for you method:
<script language="javascript" type="text/javascript">
$("#btnLoad").click(function () {
var dataForAjax = {'key' :'datakey', 'data' : 'hello'};
$.ajax({
type: "POST",
url: "Ajax__Demo.aspx/SendFile",
data: dataForAjax,
success: function (msg) {
alert(msg); // Problem with this line. It is not showing the value.
}
});
});