Problem with AJAX, JavaScript, ASP.Net MVC - javascript

Hi, everyone!
I'm writing Asp.Net MVC 2 site.
I have TimeController and TimeView, CountDownHelper for render time on TimeView page.
Also I have JavaScript that updates current time, that is used in CountDownHelper.
I need to call AJAX from this JavaScript to get current Time on server.
How I can to do it? Please help me! I must it done about several hours!
Below you may see this javaScript and in its end my try to call AJAX. I have tried to write GetServerTime.html in several ways, but anyone from which don't work. (((
//countDown.js
function calcage(secs, num1, num2)
{
s = ((Math.floor(secs / num1)) % num2).toString();
if (LeadingZero && s.length < 2)
s = "0" + s;
return "<b>" + s + "</b>";
}
function CountBack(secs)
{
if (secs < 0)
{
location.reload(true);
document.getElementById("cntdwn").innerHTML = FinishMessage;
return;
}
//difference between recieve time and current client time
diff = new Date(new Date() - clientTime);
targetD = new Date(TargetDate);
serverD = new Date(serverDate);
currentServerDate = new Date(serverD.getTime() + diff.getTime());
//targetD
leftD = new Date(targetD.getTime() - currentServerDate.getTime());
secs = leftD.getTime() / 1000;
DisplayStr = DisplayFormat.replace(/%%D%%/g, calcage(secs, 86400, 100000));
DisplayStr = DisplayStr.replace(/%%H%%/g, calcage(secs, 3600, 24));
DisplayStr = DisplayStr.replace(/%%M%%/g, calcage(secs, 60, 60));
DisplayStr = DisplayStr.replace(/%%S%%/g, calcage(secs, 1, 60));
document.getElementById("cntdwn").innerHTML = DisplayStr;
if (CountActive)
setTimeout("CountBack(" + (secs + CountStepper) + ")", SetTimeOutPeriod);
}
function putspan(backcolor, forecolor)
{
document.write("<span id='cntdwn' style='background-color:" + backcolor +
"; color:" + forecolor + "'></span>");
}
if (typeof (BackColor) == "undefined")
BackColor = "white";
if (typeof (ForeColor) == "undefined")
ForeColor = "black";
if (typeof (TargetDate) == "undefined")
TargetDate = "12/31/2020 5:00 AM";
if (typeof (serverDate) == "undefined")
serverDate = "12/31/2020 5:00 AM";
if (typeof (DisplayFormat) == "undefined")
DisplayFormat = "%%D%% Days, %%H%% Hours, %%M%% Minutes, %%S%% Seconds.";
if (typeof (CountActive) == "undefined")
CountActive = true;
if (typeof (FinishMessage) == "undefined")
FinishMessage = "";
if (typeof (CountStepper) != "number")
CountStepper = -1;
if (typeof (LeadingZero) == "undefined")
LeadingZero = true;
CountStepper = Math.ceil(CountStepper);
if (CountStepper == 0)
CountActive = false;
var SetTimeOutPeriod = (Math.abs(CountStepper) - 1) * 1000 + 990;
putspan(BackColor, ForeColor);
var dthen = new Date(TargetDate);
var dtServ = new Date(serverDate);
var dnow = new Date();
if (CountStepper > 0)
ddiff = new Date(dnow - dthen);
else
ddiff = new Date(dthen - dtServ);
//ddiff = new Date(TargetDate - serverDate);
//ddiff = new Date(dthen - dnow);
gsecs = Math.floor(ddiff.valueOf() / 1000);
CountBack(gsecs);
alert("Start");
alert(serverDate);
//AJAX CALL ????
//How to call async JavaScript?
//Which must be GetServerTime.html
$.get('Views/GetServerTime.html', function(data) {
serverDate = data;
clientTime = new Date();
});
alert(serverDate);**

Normally you don't access your views directly. And the view is usually an .ASPX file.
So
$.get('Views/GetServerTime.html',...
Becomes
$.get('/GetServerTime/',...
For the Views/GetServerTime/Index.aspx view and the getserverTimeController.cs controller with a default Action of Index.
But I'm guessing that's not the only issue you have?...
Edit
Also you should probably use JSON for this. You can use the System.Web.Mvc.JsonResult to automatically send your result as JSON and jQuery will process and convert this JSON to javascript objects.
$.get('/GetServerTime/',
function (data)
{
if (data.HasError == false)
{
$("#resultDiv").html(data.ServerTime);
}
}, "json");
Your MVC Action can look like this...
public JsonResult Index(string id)
{
JsonResult res = new JsonResult();
res.JsonRequestBehavior = JsonRequestBehavior.AllowGet;
res.Data = new { ServerTime = DateTime.Now(), HasError = false };
return res;
}
The above is approximate since I don't have a compiler.

First of all, I'm not sure "GetServerTime.html" will successfully give you the current time. Are you sure its the name of the page that you want? Unless you have your Routing set to handle that URL pattern. As Kervin says below.
Also, the body of the "function(data)" method is the callback that gets called when the ajax function returns.
As for your page that returns the server date/time, you'll need to decide what format it will return: XML or JSon. Then your controller would return that.
public class DateController : Controller {
public ActionResult CurrentDate()
{
var returnJson = new
{
currentDate = DateTime.Now.ToString()
}
return Json(returnJson, JsonRequestBehavior.AllowGet);
}
}
then your .get function would look like:
$.get('/Date' function(data) {
theDate = data.currentDate;
});

Related

How to Execute Javascript inside html automatically and use ajax to send the variables into php?

I have found a java script that can measure user download speed and it is very close to the real speed and here is the code.
//JUST AN EXAMPLE, PLEASE USE YOUR OWN PICTURE!
var imageAddr = "http://www.kenrockwell.com/contax/images/g2/examples/31120037-5mb.jpg";
var downloadSize = 4995374; //bytes
function ShowProgressMessage(msg) {
if (console) {
if (typeof msg == "string") {
console.log(msg);
} else {
for (var i = 0; i < msg.length; i++) {
console.log(msg[i]);
}
}
}
var oProgress = document.getElementById("progress");
if (oProgress) {
var actualHTML = (typeof msg == "string") ? msg : msg.join("<br />");
oProgress.innerHTML = actualHTML;
}
}
function InitiateSpeedDetection() {
ShowProgressMessage("Loading the image, please wait...");
window.setTimeout(MeasureConnectionSpeed, 1);
};
if (window.addEventListener) {
window.addEventListener('load', InitiateSpeedDetection, false);
} else if (window.attachEvent) {
window.attachEvent('onload', InitiateSpeedDetection);
}
function MeasureConnectionSpeed() {
var startTime, endTime;
var download = new Image();
download.onload = function () {
endTime = (new Date()).getTime();
showResults();
}
download.onerror = function (err, msg) {
ShowProgressMessage("Invalid image, or error downloading");
}
startTime = (new Date()).getTime();
var cacheBuster = "?nnn=" + startTime;
download.src = imageAddr + cacheBuster;
function showResults() {
var duration = (endTime - startTime) / 1000;
var bitsLoaded = downloadSize * 8;
var speedBps = (bitsLoaded / duration).toFixed(2);
var speedKbps = (speedBps / 1024).toFixed(2);
var speedMbps = (speedKbps / 1024).toFixed(2);
ShowProgressMessage([
"Your connection speed is:",
speedBps + " bps",
speedKbps + " kbps",
speedMbps + " Mbps"
]);
}
}
I have really no experience with java script at all, First, I want to edit this code to execute without showing any messages at all and then I want it to run automatically in an empty html and using ajax to redirect page to a ( url + speedMbps javascript variable ).
For example, if the url is http://url.com/get.php?speed= and the speedMbps = 23 then I want the redirect url to look like that http://url.com/get.php?speed=23
Thank you very much for your help

How to set a cookie that prevents further javascript alerts?

I have this code for detecting android:
var mobile = (/android/i.test(navigator.userAgent.toLowerCase()));
if (mobile){
alert("Message to android users");
}
...but how do I get that script to also set a cookie so the android user doesn't continue getting the alert (either on reloading the page, returning later to the page, or navigating to other pages which have the alert)?
I also have this, which uses a cookie to avoid a user viewing a "welcome page" they've already seen:
var RedirectURL = "http://www.example.com/real-home-page.html";
var DaysToLive = "365";
var CookieName = "FirstVisit";
function Action() {
location.href = RedirectURL;
}
DaysToLive = parseInt(DaysToLive);
var Value = 'bypass page next time';
function GetCookie() {
var cookiecontent = '';
if(document.cookie.length > 0) {
var cookiename = CookieName + '=';
var cookiebegin = document.cookie.indexOf(cookiename);
var cookieend = 0;
if(cookiebegin > -1) {
cookiebegin += cookiename.length;
cookieend = document.cookie.indexOf(";",cookiebegin);
if(cookieend < cookiebegin) { cookieend = document.cookie.length; }
cookiecontent = document.cookie.substring(cookiebegin,cookieend);
}
}
if(cookiecontent.length > 0) { return true; }
return false;
}
function SetCookie() {
var exp = '';
if(DaysToLive > 0) {
var now = new Date();
then = now.getTime() + (DaysToLive * 24 * 60 * 60 * 1000);
now.setTime(then);
exp = '; expires=' + now.toGMTString();
}
document.cookie = CookieName + '=' + Value + exp;
return true;
}
if(GetCookie() == true) { Action(); }
SetCookie();
Can the second script be adapted and combined into the first to do something like:
function Action() {
don't-open-that-alert-again;
I've googled and found some js cookie scripts, but all over 100K. Prefer something as succinct as the above.

set cookie on page to show bootstrap popup once a day

I'm learning JavaScript and I see that this question has been asked many times, but I can't get this to work for me.
What I want to do is, show a bootstrap modal once a day.
What I have so far is:
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var ca = document.cookie.split(';');
for(var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(name) == 0) return c.substring(name.length, c.length);
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Now, if I change the last return true; to return false; my modal does not show up.
The way it is now I see the modal every time.
What am I doing wrong?
How can I fix this?
function setCookie(cookiename, cookievalue, expdays) {
var d = new Date();
d.setTime(d.getTime()+(expdays * 24 * 60 * 60 * 1000));
var expires = "expires=" + d.toGMTString();
document.cookie = cookiename + "=" + cookievalue + "; " + expires;
}
function getCookie(cookiename) {
var name = cookiename + "=";
var startPos = document.cookie.indexOf(name);
if(startPos == -1) return null;
startPos+=(name.length);
if(document.cookie.indexOf(";",startPos) == -1){
return document.cookie.substring(startPos,document.cookie.length);
}
else{
return document.cookie.substring(startPos,document.cookie.indexOf(';',startPos));
}
return null;
}
//I want to check if there is a cookie.
//if I have not set a cookie, I want to show my modal,
//if there is a cookie then return;
//The cookie should expire in one day.
function checkCookie() {
var showed = getCookie("showed");
if (showed != null && showed != "") {
var date = new Date(showed).getDate();
var currentDate = new Date().getDate();
if (currentDate > date) {
return true;
}
return false;
}
return true;
}
Also when setting cookie,
use
setCookie('showed',new Date().toGMTString(),1);
because we are using the value of cookie, not the expire time of cookie to check. So the value must be a datestring

passing current timer's timing to the next page

How would i pass my current timer's timing into the next page?
Timer code
var expires = new Date();
expires.setSeconds(expires.getSeconds() + 60); // set timer to 60 seconds
var counter = setInterval(timer, 1);
function timer() {
var timeDiff = expires - new Date();
if (timeDiff <= 0) {
clearInterval(counter);
document.getElementById("timer").innerHTML = "00:00";
return;
}
var seconds = new Date(timeDiff).getSeconds();
var milliSeconds = (new Date(timeDiff).getMilliseconds()/10).toFixed(0);
var seconds = seconds < 10 ? "0" + seconds: seconds;
var milliSeconds = milliSeconds < 10 ? "0" + milliSeconds: milliSeconds;
document.getElementById("timer").innerHTML = seconds + ":" + milliSeconds; // watch for spelling
}
I'm using
<h3 style="color: #ff0000; margin: 0; padding: 0; font-size: 100%;font-weight:normal; font-family: robotolight;"> You have <div id="timer"></div> to complete the game!
in my html.
Is there a way to pass div id='timer'> into the next page?
Thanks.
Reloading the page or loading a new page means reloading javascript since it is runs in the context of the current page. There is good way to pass along javascript variables to a new page; it requires some form of data persistence. Cookies and localStorage are two of the most common ways of persisting data client-side.
Client cookies are written to the browser cache and are transparent in HTTP headers. LocalStorage is a newer mechanism but well supported, allowing up to 5MB of browser storage without passing in headers.
In your use case, instead of storing the timer it would probably make sense to store the timestamp when the timer was started. That way it can be recalculated in the next page from this one static start value.
var timerStart;
var expireDate = new Date();
function displayTimer(){
var now = new Date().getTime();
var timerStart = timerStart || cookieTimer();
val timeDiff = now - timerStart;
document.getElementById("timer").innerHTML = timeDiff.toString();
if(timeDiff > expireDate.getTime()) clearInterval(timerInterval);
}
val timerInterval = setInterval(displayTimer, 1);
// Using cookies
function cookieTimer(){
function getCookie(cname) {
var name = cname + "=";
var ca = document.cookie.split(';');
for(var i=0; i<ca.length; i++) {
var c = ca[i];
while (c.charAt(0)==' ') c = c.substring(1);
if (c.indexOf(name) != -1) return c.substring(name.length,c.length);
}
return "";
}
function setCookie(cname, cvalue, expireDate) {
var d = new Date();
d.setTime(d.getTime() + expireDate.getTime());
var expires = "expires="+d.toUTCString();
document.cookie = cname + "=" + cvalue + "; " + expires;
}
var timerCookie = getCookie("timer");
if(timerCookie !== "") return new Date(timerCookie).getTime());
else {
setCookie("timer", timerStart, expireDate);
return new Date().getTime();
}
}
// Using localStorage
function localStorageTimer(){
function setLocalStorageObject(key, obj, expireDate){
obj.expires = expireDate.getTime();
localStorage.setItem(key, JSON.stringify(obj));
}
function getLocalStorageObject(key){
val item = localStorage.getItem(key);
if(item) return JSON.parse(item);
else return {};
}
var timerLocal = getLocalStorageObject("timer");
var now = new Date().getTime();
if(timerLocal && timerLocal.startTime && timerLocal.expires > now) return timerLocal.startTime;
else {
setLocalStorageObject("timer", { startTime: now });
return now;
}
}

Refreshing KML data in Google Maps V3

I have a map that I have ported from V2 to V3 and I am trying to update the code to refresh the KML data at a set time. In this case every 30 secs. It is just suppose to update the data on the map and show the countdown for when the next update happens.
Here is a working version of how it is suppose to work in V2.
V2 EXAMPLE
Here is the relevant code in the V3 script I have updated but it is not working. I am not getting any errors so I am not sure what I am doing wrong. This is working on V2 but I can't get it to work with V3. What am I missing and overlooking?
//This calls genkml.php on every refresh cycle to generate a new kml file
function UpdateKML() {
//document.getElementById('TheDiv').innerHTML = '0';
var xmlhttp=false;
if (!xmlhttp && typeof XMLHttpRequest!='undefined') {
try {
xmlhttp = new XMLHttpRequest();
} catch (e) {
xmlhttp=false;
}
}
if (!xmlhttp && window.createRequest) {
try {
xmlhttp = window.createRequest();
} catch (e) {
xmlhttp=false;
}
}
xmlhttp.open("GET", "genkml.php?force=" + force + "&ofd=" + KMLdate + "&nsd=" + NSdate + "&dbg=" + dbg + "&rand="+(new Date()).valueOf(),true);
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4) {
var resp = xmlhttp.responseText;
//if (resp === undefined) resp = ''; // If we get a bad response, just set resp to nothing
if (dbg == 'y') { // Check if we want debug info
var tmpresp = resp;
if (tmpresp === undefined) tmpresp = ' ';
if (document.getElementById('div1') == null) { // Check if debug div exists, if not add it to end of body
var divTag = document.createElement("div");
divTag.id = "div1";
divTag.innerHTML = 'Response Status: ' + xmlhttp.status + '<br />' + tmpresp;
document.body.appendChild(divTag);
} else { // Otherwise just update the info
document.getElementById('div1').innerHTML = 'Response Status: ' + xmlhttp.status + '<br />' + tmpresp;
}
} else { // Else check if debug div exists and remove it (will take an update to remove
if (document.getElementById('div1') != null) document.body.removeChild(document.getElementById("div1"));
}
if (resp !== undefined) { // Make sure we got data
KMLdate = resp.split("|")[0].split("~")[0];
NSdate = resp.split("|")[0].split("~")[1];
updateHTML(resp); // This calls the updateHTML function if there is info returned
}
}
}
xmlhttp.send(null);
// add back overlays
nyLayer = new google.maps.KmlLayer(null);
nyLayer.setMap(null); // Remove overlays
var nyLayer = new google.maps.KmlLayer(URLToKML + "?rand="+(new Date()).valueOf(),
{
suppressInfoWindows: false,
map: map,
preserveViewport: true,
zIndex: 999
});
// Time overlayed on map - could be in updateHTML() to just show when .kml read last
var time = CurrentTime ("B", "12a", true, TZOffset)
document.getElementById('currenttime').innerHTML = time;
}
function CurrentTime (type, hours, secs, ofs) {
/*
type (char) hours (char) secs (bool) ofs (num)
"U"-UTC "24"=24 hr time true=hh:mm:ss 0=hours from UTC
"B"-User's Browser "12"=12 hr time false=hh:mm
"S"-Web Site "12a"=am/pm
*/
if (type == null){ type = "B"; } // These are the defaults
if (hours == null){ hours = "12a"; }
if (secs == null){ secs = true; }
if (ofs == null){ ofs = 0; }
var currentHour = 0;
var currentMinute = 0;
var currentSecond = 0;
var time = 0;
var currentDate = new Date();
if (type == "U") {
currentHour = currentDate.getUTCHours(); // UTC
} else if (type == "B") {
currentHour = currentDate.getHours(); // Viewer's time
} else {
currentHour = currentDate.getUTCHours() + ofs; // your local time
if(currentHour < 0) { currentHour = currentHour + 24;}
}
currentMinute = currentDate.getMinutes();
currentMinute = (currentMinute < 10 ? "0" : "") + currentMinute;
if (hours == "24") {
if(currentHour == 24) { currentHour = 0 }; // use if wanting 24 hour time
currentHour = (currentHour < 10 ? "0" : "") + currentHour;
} else if (hours == "12") {
if(currentHour == 0) currentHour = 12;
currentHour = (currentHour < 10 ? "0" : "") + currentHour;
} else {
if(currentHour == 0) currentHour = 12; // else no leading zero for am/pm
}
time = currentHour + ":" + currentMinute;
if (secs) {
currentSecond = currentDate.getSeconds();
currentSecond = (currentSecond < 10 ? "0" : "") + currentSecond;
time = time + ":" + currentSecond;
}
if (hours == "12a") {
time = time + " " + (currentHour > 12 ? "PM" : "AM");
}
return time;
}
//This function is only used if you leave the debug checkbox below
// You can remove this function and the checkbox and set the debug
// mode using the dbg=y query parameter
function debug(obj){
if (obj.checked) {
dbg='y';
} else {
dbg='n';
if (document.getElementById('div1') != null) document.body.removeChild(document.getElementById("div1"));
//document.getElementById('TheDiv').innerHTML = '';
}
}
//This function is only used if you leave the Force Update checkbox below
// You can remove this function and the checkbox and set the force
// mode using the force=y query parameter
function forceupdate(obj){
if (obj.checked) {
force='y';
} else {
force='n';
}
}
//This function parses out the query parameter value
function gup( name ){
name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
var regexS = "[\\?&]"+name+"=([^&#]*)";
var regex = new RegExp( regexS );
var results = regex.exec( window.location.href );
if( results == null )
return "";
else
return results[1];
}
Here is a link to the full .js map code for V3 if anyone needs to see it.
V3 NSGAMP CODE
V3 FULL PAGE
EDIT: I think it has to do with this snippet of code that is suppose to remove then add the updated KML data to the map.
This was in V2 which is depreciated now.
// add back overlays
map.removeOverlay(geoXml); //Remove overlays
geoXml = new GGeoXml(URLToKML + "?rand="+(new Date()).valueOf() ); //rand is used to trick google maps into thinking this is a new KML (don't use cache version)
map.addOverlay(geoXml); //Add the new data from the newly generated KML
Code I updated for V3 replacing the above depreciated V2 snippet which was found by searching. Not sure if this is correct but it was all I could find.
// add back overlays
nyLayer = new google.maps.KmlLayer(null);
nyLayer.setMap(null); // Remove overlays
function refresh(layer) {
var nyLayer = new google.maps.KmlLayer(URLToKML + "?rand="+(new Date()).valueOf(),
{
suppressInfoWindows: false,
map: map,
preserveViewport: true,
zIndex: 999
});
}
I got it sorted and working and I knew it was a simple edit but I was having a really difficult time finding a solution. If anyone else this could help this is what I did.
Changed this in the V2 version.
updateHTML(resp); //This calls the updateHTML function if there is info returned
}
}
}
xmlhttp.send(null);
// add back overlays
map.removeOverlay(geoXml); //Remove overlays
geoXml = new GGeoXml(URLToKML + "?rand="+(new Date()).valueOf() ); //rand is used to trick google maps into thinking this is a new KML (don't use cache version)
map.addOverlay(geoXml); //Add the new data from the newly generated KML
To this in the V3 version.
updateHTML(resp); // This calls the updateHTML function if there is info returned
}
//remove layer
window.nyLayer.setMap(null);
//change its url so that we would force the google to refetch data
window.nyLayer.url = URLToKML + "?rand="+(new Date()).valueOf();
//and re-add layer
window.nyLayer.setMap(window.map);
}
}
xmlhttp.send(null);
The map.removeOverlay and map.addOverlay is depreciated in V3 so it took me while to find the replacement.
Or you can simplify it even further and use:
window.nyLayer.url = URLToKML + '&ver=' + Date.now();

Categories

Resources