Unable to get the correct Ans as i am getting correct result from the Jquery variable "shortly" but when i am Synchronise with function "serverSync" all will set to 0:0:0 i have checked both having a same date.
ref. site
http://keith-wood.name/countdown.html
here is my code
[WebMethod]
public static String GetTime()
{
DateTime dt = new DateTime();
dt = Convert.ToDateTime("April 9, 2010 22:38:10");
return dt.ToString("dddd, dd MMMM yyyy HH:mm:ss");
}
html file
<script type="text/javascript" src="Scripts/jquery-1.3.2.js"></script>
<script type="text/javascript" src="Scripts/jquery.countdown.js"></script>
<script type="text/javascript">
$(function() {
var shortly = new Date('April 9, 2010 22:38:10');
var newTime = new Date('April 9, 2010 22:38:10');
//for loop divid
///
$('#defaultCountdown').countdown({
until: shortly, onExpiry: liftOff, onTick: watchCountdown, serverSync: serverTime
});
$('#div1').countdown({ until: newTime });
});
function serverTime() {
var time = null;
$.ajax({
type: "POST",
//Page Name (in which the method should be called) and method name
url: "Default.aspx/GetTime",
// If you want to pass parameter or data to server side function you can try line
contentType: "application/json; charset=utf-8",
dataType: "json",
data: "{}",
async: false,
//else If you don't want to pass any value to server side function leave the data to blank line below
//data: "{}",
success: function(msg) {
//Got the response from server and render to the client
time = new Date(msg.d);
alert(time);
},
error: function(msg) {
time = new Date();
alert('1');
}
});
return time;
}
function watchCountdown() { }
function liftOff() { }
</script>
You're setting the server time equal to the time you're counting down towards.
Since the new "serverSync" time and the "until" time are the same, the countdown will just be 0's across the board.
Related
I am trying to find a way to keep my session alive when Controller is taking long time to come back with results. My Javascript on button click looks like below:
function OnClick(s, e) {
positionDate = ReportingPositionDate.GetDate().toDateString();
if (true) {
$.ajax({
type: "POST",
url: "#Url.Action("DataFileUpload", "ImportData")",
data: JSON.stringify({ positionDate: positionDate }),
dataType: "text",
contentType: "application/json; charset=utf-8",
beforeSend: function () { lpImport.Show(); },
success: function (msg) {
debugger;
ImportDataGridView.PerformCallback();
ImportSuccessMessage.SetVisible(true);
ImportSuccessMessage.SetText(msg);
lpImport.Hide();
},
Error: function (xhr) {
alert(xhr)
ImportDataGridView.PerformCallback();
}
});
}
}
basically session times out before I get Success. I would like to silently keep session alive.
Thanks all.
I searched the web for same. There were responses but they were incorrect.
I was eventually able to tweak one of them, and this is the result:
-- Create an asp.net mvc app;
add the following to the home controller:
[HttpPost]
public JsonResult KeepSessionAlive()
{
return new JsonResult { Data = "Postback " + on " + DateTime.Now};
}
----Add the following to index.cshtml:
<div id="myDiv"></div>
#section scripts{
<script src="~/SessionUpdater.js"></script>
<script type="text/javascript">
SessionUpdater.Setup('#Url.Action("KeepSessionAlive","Home")');
</script>
}
-- reference the following js file [in addition to referencing jquery]
SessionUpdater = (function () {
var clientMovedSinceLastTimeout = false;
var keepSessionAliveUrl = null;
//var timeout = 5 * 1000 * 60; // 5 minutes
var timeout = 15000; // 15 seconds for testing
function setupSessionUpdater(actionUrl) {
// store local value
keepSessionAliveUrl = actionUrl;
// alert(actionUrl);
// setup handlers
listenForChanges();
// start timeout - it'll run after n minutes
checkToKeepSessionAlive();
}
function listenForChanges() {
$("body").on("mousemove keydown", function () {
clientMovedSinceLastTimeout = true;
});
}
// fires every n minutes - if there's been movement ping server and restart timer
function checkToKeepSessionAlive() {
setTimeout(function () { keepSessionAlive(); }, timeout);
}
function keepSessionAlive() {
// if we've had any movement since last run, ping the server
if (!clientMovedSinceLastTimeout && keepSessionAliveUrl != null) {
$.ajax({
type: "POST",
url: keepSessionAliveUrl,
success: function (data) {
$('#span').text(data);
$('#myDiv').append('<br/>' + data);
// reset movement flag
clientMovedSinceLastTimeout = false;
// start listening for changes again
listenForChanges();
// restart timeout to check again in n minutes
checkToKeepSessionAlive();
},
error: function (data) {
alert("ERROR");
console.log("Error posting to " & keepSessionAliveUrl);
}
});
}
else {
clientMovedSinceLastTimeout = false;
listenForChanges();
checkToKeepSessionAlive();
}
}
// export setup method
return {
Setup: setupSessionUpdater
};
})();
Using a javascript plugin Fullcalendar, and I'm trying to load data into the events handle in the javascript plugin. The data is being processed but isn't being displayed in the calendar.
If I was to guess the issue, I think it would have to do with my date format being returned, to the full calendar plugin. Is it supposed to be returned in unixtimestamp? Here is the Json result.
They're valid unixtimestamps.
Here is my controller.
[AcceptVerbs(HttpVerbs.Get)]
public JsonResult CalendarData()
{
DateTime start = new DateTime(1970, 1, 1);
DateTime end = new DateTime(1970, 1, 1);
start = start.AddSeconds(double.Parse(Request["start"]));
end = end.AddSeconds(double.Parse(Request["end"]));
// call middle tier/orm/whatever to get data from source
List<webby.Models.Calendar> list = SearchForEvents(start, end);
return Json(list, JsonRequestBehavior.AllowGet);
}
private List<webby.Models.Calendar> SearchForEvents(DateTime start, DateTime end)
{
var eventList = (from e in db.Calendars
select new
{
ID = e.ID,
title = e.title,
start = start,
end = end
}).AsEnumerable().Select(x=> new webby.Models.Calendar{ID=x.ID, title =x.title, start = x.start, end =x.end}).ToList();
return (eventList);
}
And my fullcalendar plugin:
<script>
$(document).ready(function () {
$('#calendar').fullCalendar({
height: 170,
selectable: true,
editable: true,
defaultView: 'basicWeek',
events: "/Home/CalendarData",
dayClick: function (date, jsEvent, view) {
$.ajax(
{
url: '#Url.Action("Index","Home")',
type: "POST",
data: JSON.stringify({ date: date }),
contentType: "application/json; charset=utf-8",
cache: false
}).success(function (response) {
$("#modalLoad").html(response);
$("#myModal").modal();
}).error(function (a,b,c) {
alert(a.responseText);
alert(b);
alert(c);
});
}
});
});
</script>
I'm not certain that you can use UNIX timestamps here. I think it has to be something moment() can parse. See http://momentjs.com/docs/#/parsing/
I had populated an ASP.net dropdown list with AJAX now I need to get the Id to store in into the database in a C# method, (I'm using LINQ)
This is my webmethod
[WebMethod]
public static ArrayList GetLanguageList()
{
ArrayList lstArrLanguage = new ArrayList();
IQueryable<Common.Town> myList = new SupplierBL().GetTowns();
foreach(Common.Town t in myList)
{
string name = t.Name;
string id = t.TownId.ToString();
lstArrLanguage.Add(new ListItem(name, id));
}
return lstArrLanguage;
}
My test.aspx code
<script language="javascript" type="text/javascript">
$(document).ready(function () {
$.ajax({
type: "POST",
url: "test.aspx/GetLanguageList",
data: '',
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#ddlLanguage").empty().append($("<option></option>").val("[-]").html("Please select"));
$.each(msg.d, function () {
$('#<%=ddlLanguage.ClientID%>').append($("<option></option>").val(this['Value']).html(this['Text']));
});
},
error: function () {
alert("An error has occurred during processing your request.");
}
});
});
</script>
You can't get selected value from DropDownList if you adding options in javaScript. You can try the following
string selectedValue = Request.Form[ddlLanguage.UniqueID];
This question may be useful also.
If you populate the value of dropdown via ajax than it can't be available on Server Side because the page doesn't postback during ajax request.
In order to get the value of dropdown in C# use below snippets :
String _value = Convert.ToString(Request[ddlLanguage.ClientID]);
Hope this will help !!
Here is my ajax call:
var totalCost = 0;
function GetTotalCost(start, end, rID)
{
$.ajax({
url: '#Url.Action("CalculateTotalcost")',
type: 'POST',
data: JSON.stringify({ start:start, end:end, rID:rID}),
dataType: 'json',
processdata: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { totalCost = data; }
// error: function (xhr, ajaxOptions, thrownError) { $('.datepicker1').datepicker("hide"); },
// complete: function (x, y) { $('.datepicker1').datepicker("refresh"); }
});
}
Here is my function from which I call ajax:
$('.datepicker2').datepicker({
dateFormat: 'dd/mm/yy',
firstDay: 1,
yearRange: '2012:2100',
beforeShowDay: function (date) {
var day = date.getDate();
if (day in alreadyTakenDays) {
return [false, '', alreadyTakenDays[day]];
}
else return [true, 'IsActive'];
},
onChangeMonthYear: function (year, month, inst) {
alreadyTakenDays = {};
getEvents(month, year);
},
onSelect: function (dateText, inst) {
var end = dateText.substring(0, 2);
console.log(end);
var rID = $('#RoomID').val();
console.log(rID);
var startingHole = $('#DateOne').val();
var start = startingHole.substring(0, 2);
console.log(start);
GetTotalCost(start, end, rID);
document.getElementById('TotalCost').value = totalCost.toFixed(2);
}
});
After jQuery script is executed I always get 0 for totalCount?
Why is this happening? What should I Do?
I would like to appoint totalCount to Html.TextBoxFor in ASP.NET MVC 3, that is why I need totalCount. Please help.
The ajax call is asychronous and hasn't completed when you set the value on your 'TotalCost' text box.
You should have success function handler like this to get correct total cost value:
function GetTotalCost(start, end, rID)
{
$.ajax({
url: '#Url.Action("CalculateTotalcost")',
type: 'POST',
data: JSON.stringify({ start:start, end:end, rID:rID}),
dataType: 'json',
processdata: false,
contentType: 'application/json; charset=utf-8',
success: function (data) { totalCost = data;
document.getElementById('TotalCost').value = totalCost.toFixed(2);
}
});
}
In code like this:
GetTotalCost(start, end, rID);
document.getElementById('TotalCost').value = totalCost.toFixed(2);
First line cause ajax call, but it does not wait for response and second line is executed immediately. Later, after server responded, success callback function is executed. And it will be executed after second line. That is why your total value is wrong - correct value is set to totalCost after you update TotalCost input.
Because your post is asynchronous and you are trying to set a js variable that is global to the page. Create a function that sets the variable and call it from the call back, then you will see the result.
That is because of Asynchronous ajax Request..
By the time you the event is handled , the request has not been completed yet.
Welcome to the wonderful world of AJAX.
I'm doing jQuery autocomplete. Works fine if I put hard codded JSON array. But it fails when I pass the array from c#. Please help, I spend enough time with it and I'm stuck!
Here is my jQuery code in AutoComplete.aspx
<script type="text/javascript">
$(document).ready(function () {
var msgbox = $("#status");
$.ajax({
type: "POST",
//Page Name (in which the method should be called) and method name
url: "AutoControl.aspx/GetData",
//else If you don't want to pass any value to server side function leave the data to blank line below
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (msg) {
$("#status").val(msg.d);
}
});
$('#<%=tags.ClientID%>').autocomplete(["c++", "java", "php", "coldfusion"], {
width: 320,
max: 4,
highlight: false,
multiple: true,
multipleSeparator: " ",
scroll: true,
scrollHeight: 300
});
});
</script>
Here is my C# code in AutoComplete.aspx.cs
[System.Web.Services.WebMethod]
public static string GetData()
{
return "\"c++\", \"java\", \"php\"";
}
How do I pass the JSON array from C# to jQuery. With this code I could retrieve the values from c# but some reason JSON is not reading the values.
I want to change this code:
$('#<%=tags.ClientID%>').autocomplete(["c++", "java", "php", "coldfusion"]
to
$('#<%=tags.ClientID%>').autocomplete([ jsonArray_from_C# ]
Have you tried returning an string array?
http://encosia.com/2011/04/13/asp-net-web-services-mistake-manual-json-serialization/
don't try to parse Json, pass the object directly.