I cannot dynamically highlight the date in calendar, only static dates highlight if I do:
eventDates[new Date('01/09/2018')] = new Date('01/09/2018')
Here is my code:
$(function() {
// An array of dates
var eventDates = [];
$.ajax({
type: "GET",
url: "#Url.Action("
GetEvents ", "
Home ")",
dataType: "json",
data: "",
success: function(data) {
$.each(data, function(i, val) {
var dd = CTD(val.Date); //CTD means convert into date
eventDates[i] = dd;
});
}
});
// convert in date
function CTD(d) {
var date = new Date(parseInt(d.substr(6)));
var month = date.getMonth() + 1;
return date.getDate() + "/" + month + "/" + date.getFullYear();
}
//eventDates[new Date('01/09/2018')] = new Date('01/09/2018');
// datepicker
$('#datepicker').datepicker({
beforeShowDay: function(date) {
var highlight = eventDates[date];
if (highlight) {
return [true, "event", 'Tooltip text'];
} else {
return [true, '', ''];
}
}
});
});
Then in the DatePicker, you are searching in the array indexes, so you will not find the date. To find the date you need to use the indexOf() method and you need to format the DatePicker date in the same format that you saved in the array:
var month = date.getMonth() + 1;
date = date.getDate() + "/" + month + "/" + date.getFullYear();
var highlight = eventDates.indexOf(date);
Instead of repeating the code to format the date, you extract the formatting code from your CTD() function into a new function:
// convert in date
function CTD(d) {
var date = new Date(parseInt(d.substr(6)));
return FD(date);
}
// format date
function FD(d) {
return d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear();
}
And finally, you want to make sure that the code for the DatePicker will only run after the Ajax result comes back, so put in a function and call it from the success of the Ajax:
$(function() {
$.ajax({
type: "GET",
url: "#Url.Action("GetEvents", "Home")",
dataType: "json",
data: "",
success: function(data) {
var eventDates = []; //An array of dates
$.each(data, function(i, val) {
eventDates[i] = CTD(val.Date); //CTD means convert into date
});
HighlighEvents(eventDates);
}
});
// convert in date
function CTD(d) {
var date = new Date(parseInt(d.substr(6)));
return FD(date);
}
// format date
function FD(d) {
return d.getDate() + "/" + (d.getMonth() + 1) + "/" + d.getFullYear();
}
// datepicker
function HighlighEvents(eventDates) {
$('#datepicker').datepicker({
beforeShowDay: function(date) {
var highlight = eventDates.indexOf(FD(date));
if (highlight > -1) {
return [true, "event", 'Tooltip text'];
} else {
return [true, '', ''];
}
}
});
}
});
Related
I have a stored procedure that selects all the fields in the table based on the date. I then created a method shown below to return the results as JSON.
[HttpGet]
public JsonResult GetResult()
{
MonthNameConverter converter = new MonthNameConverter();
string fullDate = converter.startOfMonth().ToShortDateString();
string[] split = fullDate.Split('/');
string date = "";
if(Convert.ToInt32(split[0]) < 10)
{
date = split[2] + "-0" + split[0];
}
else
{
date = split[2] + "-" + split[0];
}
var results = travelSOCC.GetLansingMileage(date).ToList();
return Json(results, JsonRequestBehavior.AllowGet);
}
However when I go to append the data to an HTML table I'm getting an unidentified result.
$(function LoadData() {
$("#LansingTable tbody tr").remove();
$.ajax({
type: 'GET',
url: '#Url.Action("GetResult")',
dataType: 'json',
data: JSON,
success: function (data) {
$.each(data, function (item) {
var rows = "<tr><td>" + item.TravelDate + "</td><td>" + item.TripType + "</td></tr>";
$("#LansingTable tbody").append(rows);
});
},
error: function (ex) {
var r = jQuery.parseJSON(response.resonseText);
alert("Message: " + r.Message);
}
})
});
Any help is greatly appreciated.
Please modify $.each(data, function(item) { as below:
$.each(data, function(idx, item) {
Please refer documentation here for more information.
I have found that when converting my arrays to JSON, there are extra square brackets that are preventing the data from being parsed.
I make an AJAX call which prepares the data server side. The C# processes the data and turns it into an array of arrays for Google Charts to process.
It is all dynamic, so I have no idea how many arrays there will be, hence I cannot hardcode the arrays and I cannot loop the client side as the performance is shocking.
I don't think the JSON parser in the JavaScript is the issue, it is in the C# I have written.
I have added two JSON links, one is the output, the other is the expected output.
My C# is:
public List<object[]> CreateJsonMultiChartData(string serial, string guid, string datefrom, string dateto)
{
var serials = _context.RawData.Where(x => x.ProjectGuid == guid).Select(x => x.SerialNumber).Distinct().ToList();
var projectUid = guid;
var from = datefrom;
var to = dateto;
//Method to return data
var g = new GetChartDataSprocs(_context, _configuration);
List<object> chartData = new List<object>();
var arrays = new List<object[]>();
foreach (var s in serials)
{
var data = g.GetChartDataFromSqlServer(s, projectUid, from, to);
foreach (var item in data)
{
var year = Convert.ToDateTime(item.ReadingDate).Year;
var month = Convert.ToDateTime(item.ReadingDate).Month;
var day = Convert.ToDateTime(item.ReadingDate).Day;
var hour = Convert.ToDateTime(item.ReadingDate).Hour;
var minute = Convert.ToDateTime(item.ReadingDate).Minute;
var second = Convert.ToDateTime(item.ReadingDate).Second;
var date = "new Date(" + year + "," + month + "," + day + "," + hour + "," + minute + "," + second + ")";
chartData.Add(
new ChartTestModel
{
ReadingDate = date,
ReadingValue = item.ReadingValue
});
};
arrays.Add(new[] { chartData });
}
return arrays;
}
My AJAX response is:
public JsonResult GetMultiChartData(string serial, string uid, string from, string to)
{
var dateFrom = Convert.ToDateTime(from).ToString("yyyy-MM-dd HH:mm:ss");
var dateTo = Convert.ToDateTime(to).AddMinutes(1).ToString("yyyy-MM-dd HH:mm:ss");
var g = new GetChartData(_context, _configuration);
var items = g.CreateJsonMultiChartData(serial, uid, dateFrom, dateTo);
//var dsItems = JsonConvert.DeserializeObject(items);
// return items;
return Json(JsonConvert.SerializeObject(items, Formatting.Indented));
}
My AJAX call is:
$.ajax({
url: 'ProjectCharts/GetMultiChartData',
datatype: 'json',
type: 'get',
async: false,
data: { section: section, uid: uid, from: from, to: to },
contentType: 'application/json; charset=utf-8',
success: function (d) {
parsedData = $.parseJSON(d);
var data = new google.visualization.arrayToDataTable([
{ label: 'Date', id: 'ReadingDate', type: 'date' }, // Use object notation to explicitly specify the data type.
{ label: 'Data', id: 'ReadingValue', type: 'number' }, [parsedData]]);
var chart = new google.visualization.LineChart(document.getElementById('chart'));
var options = multiLineChartOptions();
chart.draw(data, options);
},
error: function () {
alert("Error");
}
});
The output is at:
Current JSON Ouput
The expected output is:
Expected JSON Output
I wanted to get Json data from web method.In here i wanted to get News & Speaker both data but here only working News only.(Unable to get Speaker )
Here is my Stored Procedure
ALTER procedure [dbo].[LoadDayEvents]
#Date date
as
begin
select News,Speaker from Eventstbl
where DateToBePublished = CONVERT(date, #Date)
end
Here is my Web Method
[WebMethod, ScriptMethod]
public static string SelectEventDate(string date)
{
string News= "";
string Speaker = "";
try
{
SqlCommand comld = new SqlCommand("LoadDayEvents", conDB);
comld.CommandType = CommandType.StoredProcedure;
comld .Parameters.Add("#Date", SqlDbType.Date);
comld .Parameters["#Date"].Value = DateTime.Parse(date).Date;
if (conDB.State == ConnectionState.Closed)
conDB.Open();
News = comld .ExecuteScalar().ToString();
Speaker = comld .ExecuteScalar().ToString(); // Thisone is not working
}
catch (Exception ee) { }
finally { conDB.Close(); }
return News;
}
Here i use Ajax/Json to get it
<script type="text/javascript">
$(document).ready(function () {
var urinews = '<%= ResolveUrl("WebMethods.aspx/SelectEventDate") %>';
var localtime = new Date();
var today = localtime.getFullYear() + '/' + (localtime.getMonth() + 1) + '/' + localtime.getDate();
$.ajax({
type: "POST",
url: urinews,
data: "{ date: '" + today + "'}",
contentType: "application/json; charset=utf-8",
dataType: "json",
async: true,
cache: false,
success: function (msg) {
$("#daily_news_Selection").append("<p>" + msg.d + "</p>");
},
error: function (x, e) {
}
});
});
</script>
You could return custom class
var newsAndSpeaker = new NewsAndApeaker() { News = News, Speaker = Speaker}; //or define a custom class that has these two properties
return newsAndSpeaker;
On Javascript, you can access the two variables using
msg.d.News //news
msg.d.Speaker
Or, you could return a list of string
var newsAndSpeaker = new List<string>() { News, Speaker}; //or define a custom class that has these two properties
return newsAndSpeaker;
On Javascript, you can access the two variables as in like a array
msg.d[0] //mews
msg.d.[1] //speaker
If your question is why your second property is not getting populated, then title seems to be wrong
I have inputs and selects. For some reason, some of them are giving me a null. Here is the code:
<script type="text/javascript">
$(function () {
$('#add').on('click', function () {
$('table').append('<tr>' +
'<td><button class=\'save\'>Save</button></td>' +
'<td><input name=\'name\' id=\'companyName\' /></td>' +
'<td><input name=\'currency\' id=\'currency\' /></td>' +
'<td><input name=\'ISOCode\' id=\'ISOCode\' /></td>' +
'<td><input name=\'CalcDeadLine\' id=\'CalcDeadLine\' /></td>' +
'<td><select name=\'mealAlgorithm\' id=\'mealAlgorithm\'><option value="True">Yes</option><option value="False">No</option></select></td>' +
'<td><input name=\'breakfast\' id=\'breakfast\' /></td>' +
'<td><input name=\'halfBoard\' id=\'halfBoard\' /></td>' +
'<td><input name=\'fullBoard\' id=\'fullBoard\' /></td>' +
'<td><input name=\'adminID\' id=\'adminID\' /></td>' +
'<td><input name=\'language\' id=\'language\' /></td>' +
'<td><input name=\'approvalcid\' id=\'cid\' /></td>' +
'<td><select name=\'useSMS\' id=\'useSMS\'><option value="True">Yes</option><option value="False">No</option></select></td>' +
'<td><select name=\'active\' id=\'active\'><option value="True">Yes</option><option value="False">No</option></select></td>');
$('#add').hide();
})
});
$(".save").live("click", function () {
var name = $("#companyName").val();
var currency = $("#currency").val();
var isoCode = $("#ISOCode").val();
var calcDeadLine = $("#CalcDeadLine").val();
var mealAlgorithm = $("#mealAlgorithm").val();
var noMeal = 111;
var breakfast = $("#breakfast").val();
var halfBoard = $("#halfBoard").val();
var fullBoard = $("#fullBoard").val();
var adminID = $("#adminID").val();
var language = $("#language").val();
var cid = $("#cid").val();
var useSms = $("#useSMS").val();
var active = $("#active").val();
$.ajax({
type: "GET",
contentType: "application/json; charset=utf-8",
url: '#Url.Action("SaveCompany", "Admin")',
data: {
"CompanyName": name, "Currency": currency, "ISOCompanyCode": isoCode, "CalcDeadline": calcDeadLine,
"UseMealAlgorithm": mealAlgorithm, "NoMeal": noMeal, "Breakfast": breakfast, "HalfBoard": halfBoard,
"FullBoard": fullBoard, "AdminUserID": adminID, "ApprovalCulture": language, "ApprovalLcid": cid,
"UseSMS": useSms, "Active": active},
dataType: "json",
beforeSend: function () {
},
success: function (data) {
if (data.result == true) {
$("#GridCompany").html("Record has been saved!");
}
else {
alert("There is some error.");
}
}
})
})
In url of post everything is ok, it has true/false and every parameter with every value fulfilled.
In my controller I have
[HttpGet]
public JsonResult SaveCompany(string name, string currency, string isoCode, int calcDeadline, bool? mealAlgorithm,
int noMeal, int breakfast, int halfBoard, int fullBoard, string adminUserId, string approvalCulture,
int? approvalCid, bool? useSms, bool? active)
{
bool result = false;
try
{
result = _companyRepository.SaveCompany(name, currency, isoCode, calcDeadline, mealAlgorithm, noMeal,
breakfast, halfBoard, fullBoard, adminUserId, approvalCulture, approvalCid, useSms, active);
}
catch(Exception ex)
{
}
return Json(new { result }, JsonRequestBehavior.AllowGet);
}
Nulls are isoCode, mealAlgorithm, approvalCid.
The problem is the wrong names of the fields.
In the AJAX you pass ISOCompanyCode but in the Action you're waiting for isoCode
The same is for the other two fields (you have different names). Use the same names and it'll fix your problem.
I have the following code where the function codeaddress geocodes the text feild value and returns geocoded value , geocoded value is stored in variable example ,how will i return the variable v2 to the function call and post to asmx webservice.
<script type="text/javascript">
$(document).ready(function() {
$('#SubmitForm').submit(function() {
var geocoder;
var map;
function codeAddress(state) {
var address = document.getElementById("state").value;
geocoder.geocode( { 'address': state}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var v2=results[0].geometry.location;
alert(example);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert("Geocode was not successful for the following reason: " + status);
}
return v2;
});
var businessname = ($("#businessname").val());
var keyword = ($("#keyword").val());
var description = ($("#textarea").val());
var zipcode = ($("#zipcode").val());
var streetno = ($("#streetno").val());
var streetname = ($("#streetname").val());
var state = $('#state :selected').text();
var telephone = ($("#telephone").val());
var email = ($("#email").val());
var username = ($("#username").val());
var password = ($("#pass").val());
var repassword = ($("#pass1").val());
//data: "{'businessname':" + businessname + "'keyword':" + keyword + "}",
alert(state);
var v2=codeAddress(state);
alert(example);
var jsonobject = "{\"businessname\":\"" + businessname + "\",\"keyword\":\"" + keyword + "\",\"description\":\"" + description + "\",\"zipcode\":\"" + zipcode + "\",\"streetno\":\"" + streetno + "\",\"streetname\":\"" + streetname + "\",\"state\":\"" + state + "\",\"telephone\":\"" + telephone + "\",\"email\":\"" + email + "\",\"username\":\"" + username + "\",\"password\":\"" + password + "\",\"repassword\":\"" + repassword + "\"}";
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
});
function ajaxCallFailed(error) {
alert("error");
}
function ajaxCallSucceed(response) {
if (response.d == true) {
alert(" sucessfully saved to database");
}
else {
alert("not saved to database");
}
}
});
</script>
You call the codeAddress method with a callback. Inside codeAddress when you get value of v2, call the callback function passing it v2.
codeAddress(state,
function(v2) {
var jsonobject = "{\"businessname\":\"" + businessname/*.. use v2 in buiding jsonobject..*/;
$.ajax({
type: "POST",
url: "/BlockSeek/jsonwebservice.asmx/SubmitList",
data: jsonobject,
contentType: "application/json; charset=utf-8",
success: ajaxCallSucceed,
dataType: "json",
failure: ajaxCallFailed
});
}
);
function codeAddress(state, callback) {
var address = document.getElementById("state").value;
geocoder.geocode(...);
// ...
var v2=results[0].geometry.location;
callback(v2);
}