I have a program(c#) but the programs needs to work for every timezone, so i created a js script to know the client timezone and this is what i get (and it works) but only if only click action(example button), but i need this to work (run) on my page load is that possible?
This is my script
<script type="text/javascript">
function pageLoad() {
myFunction();
}
function myFunction() {
var localTime = new Date();
var year = localTime.getYear();
var month = localTime.getMonth() + 1;
var date = localTime.getDate();
var hours = localTime.getHours();
var minutes = localTime.getMinutes();
var seconds = localTime.getSeconds();
var calculated_date = hours + ":" + minutes + ":" + seconds;
var div = document.getElementById("demo");
div.innerText = calculated_date;
var client_date = document.getElementById("client_date");
client_date.setAttribute("value", calculated_date);
}
</script>
And this is what i tryed so far
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Thanks anyway for reading my post, hope someone can help on this issue
Yes, it is possible. All you need is to use onload() event.
This would do it
<body onload="myFunction()">
<!-- body elements here -->
</body>
You can execute any function that you want to execute on a page load. I used myFunction because that had to be executed when the page loads.
with javascript
if (document.readyState === "complete") { myFunction(); }
with jquery
$(document).ready(function(){ myFunction(); });
The problem isn't what you think. In all likelihood, this JavaScript *is*set to run when the page loads. And it's probably going to do exactly what you told it to do. The problem is what else you're doing. Note these three lines:
Page.ClientScript.RegisterStartupScript(this.GetType(), "myFunction", "myFunction()", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
What you're doing here is:
Set the JavaScript to run when the page loads.
Capture the value of a TextBox from before the page loaded.
Abandon the page entirely and redirect to another page.
So even if the JavaScript code would run, you're not capturing the value it sets. And even if you were capturing that value, you abandon the entire page before it even loads and redirect the user to a different page.
You need to better understand the difference between server-side code, which runs on the server in its entirety before delivering a page to the client... and client-side code, which runs after a page has loaded on the client.
If you need this information from the client, you'll need to get it from client-side code. This code will need to run in a loaded page and then send the value back to the server in some way. Either the page has to execute and then perform the redirect from client-side code, or (probably better) the page can run as normal, make an AJAX post to the server to notify you of this information (time zone), and then the server can respond to the AJAX request with any data the client-side code needs to adjust the page accordingly.
It's not really clear what you're customizing based on the time zone or when you need to know the time zone. But it is clear that you need the client-side code to execute before you can retrieve that value from the client.
Use System.Web.ScriptManager Like this :
Page.ClientScript.RegisterStartupScript(this, this.GetType(), Guid.NewGuid().ToString(), "myFunction();", true);
Session["Data"] = client_date.Text;
Response.Redirect("Welcome.aspx");
Well you can't store the value within a hidden field and then read result, but what you can do is store the timezone offset as a cookie and then read that on the server after the page reloads.
This article explains it perfectly
http://prideparrot.com/blog/archive/2011/9/how_to_display_dates_and_times_in_clients_timezone
Related
I have a C# Property CategoryID, I want to set it's value in Javascript.
I am trying to set the value CategoryID like below:
var sPath = window.location.pathname;
var catId = null;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if (sPage == 'xyz.aspx')
{
<%=CommonUtility.CategoryID=4%>;
}
else if(sPage == 'zxy.aspx')
{
<%=CommonUtility.CategoryID=5%>;
}
But by this method I always get the value of CategoryID= 5(which is in else block) .
Please suggest me how can get the Property value based on condition.
You can't set a C# property from a client-side (js). You may use ajax to do some work, but you simply can't manipulate server-side code.
edit:
if you still wonder how it's possible you get a value, see Mike's explanation of that fact. But the truth remains. You can't. It's impossible. If you want to know the longer explanation, see how asp.net actually works, it's lifecycle etc. Simple way of putting it would be like this:
A user sends a request to the server using his browser. The server receives it, creates a requested page and instantiates needed classes etc. Then it's gets parsed and sent to the client as html (and other resources of course, like images, css...). The instantiated page class CAN'T be accessed and modified afterwards by the client, because it's already flushed by the server. Every request creates a new instance. There's no way of interacting js with c# anyway. Can you imagine what it would be like, if you could use some js to modify C# on a remote server? It doesn't make sense at all.
You cannot set properties in your code-behind using client-side script this way. The only way to do something like that would be to use AJAX to send data to your server, although I'm pretty sure that's not appropriate for your case.
When you call <%=CommonUtility.CategoryID = 4%>, the server actually executes that statement when it is parsing the page before it sends it to the client. The reason that the property value is 5 is that both of those statements get executed, regardless of the logic in your Javascript if block. Your client side code will not actually be executed by the browser until the server has already parsed both of those tags, which at that point it would be too late to accomplish what you want anyways.
Is there any reason that you simply can't do all of this in the code-behind on page load? Is there some reason you feel like this has to be handled in JS?
Edit:
If you are unable to access the code-behind file (.aspx.vb or .aspx.cs) then simply use a server script block in the top of your .aspx page
<%
If (Request.Path.ToLower().Contains("xyz.aspx")) Then
CommonUtility.CategoryId = 4
ElseIf (Request.Path.ToLower().Contains("zxy.aspx")) Then
CommonUtility.CategoryId = 5
End If
%>
You can't set the C# variable from client script, because all the server code runs first, then the page is sent to the browser.
The client code will end up looking like this:
var sPath = window.location.pathname;
var catId = null;
var sPage = sPath.substring(sPath.lastIndexOf('/') + 1);
if (sPage == 'xyz.aspx')
{
4;
}
else if(sPage == 'zxy.aspx')
{
5;
}
}
I have a jQuery Countdown Timer that I am using, and I need to be able to access my Database and perform some calculations and then return the result:
$('#expireMessage').countdown({until: shortly,
expiryText: '<div class="over">It\'s all over</div>'});
$('#expireMessageStart').click(function() {
shortly = new Date();
shortly.setSeconds(shortly.getSeconds() + 5.5);
$('#expireMessage').countdown('change', {until: shortly});
});
Now, the above code just displays a countdown timer, and counts down. And when it hits
00:00:00
it displays a message "It's all over".
But what I need it to do is display a different message depending on the result of the DB calculations.
The DB work I can do, but I'm not sure how to go about retrieving that info from the database when using jQuery. I'd really appreciate your help.
Thank you
You need to set up something on the server side to talk to the database for you, then return the result in JSON format. What that something is depends on what your server-side code is written in. Are you using PHP? Java? ASP.NET?
I work primarily in ASP.NET, so one way I might tackle this is adding a WebMethod to my page that executes a database query, builds the message, serializes it to JSON, and returns it to the client.
In your JavaScript, you'll want to execute either an XMLHttpRequest (if you're using regular JavaScript) or a jQuery AJAX request.
Here's a very simple example of what a jQuery AJAX call might look like:
$.ajax({
url: 'http://mysite.com/getmymessage',
success: function( data ) {
// Here's where you'd update your countdown display, but I'm just writing to the console
console.log( 'The server says: ' + data.myDbResult );
}
});
Please let me ask something. I just confused for what is the difference of javascript, JQuery and code behind attributes.
for example :
ASPX
<tbody id="toggleSup" runat="server">
C#
toggleSup.Visible = false;
--------------------------------------- OR ---------------------------
C#
CallScript((string)(Session["toggle"]));
private void CallScript(string str)
{
string scriptx = "<SCRIPT LANGUAGE='javascript'>";
scriptx += "toggle('" + str + "');";
scriptx += "</script>";
ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "scriptx", scriptx, false);
}
Script
function toggle(para1) {
if (para1 == 0) {
$('#toggleSup').hide();
}
else {
$('#togglePO').hide();
}
}
for these two difference things, most of the developers use script. Why? Actually C# code is only one row. different thing is if I use script, no need to use runat="server" but if I used code behind, need to use runat = "server". So I think there may be definately have advantages. Please explain me, if possible...
Thanks
If you say toggleSup.Visible = false; in your C#, then the toggleSup does not even get rendered to the DOM. Meaning it's not on the page at all. If you want to make that element visible from some action on the page, then you have to make a round trip to the server and re-render all (postback) or part (ajax) of the page.
Alternatively, if you allow the toggleSub control to be manipulated from JavaScript (jQuery in this case), then it's part of the DOM and can be acted upon in response to other events on the page. Mainly, this means that the client browser can do things without asking the server for more HTML.
So, the C# method looks simpler to code, but the jQuery method is more flexible if you need a rich client-side experience.
When using "script", the browser performs the work. With runat server, then the browser must either get/post a HTTP request or do "AJAX" to the server.
Using "script" is much faster and is easier to maintain state.
In simple words Java Script and JQuery code runs on the client browser whereas C# code runs on the server.
how to automatically redirect an ASP.NET page to another after 1 minute using c# code.
You can use something like this:
<meta http-equiv="Refresh" content="60; url=http://your.new/url/here" />
The "60" is the time in seconds to wait before page redirect.
Try this one line code:
Here 5 means redirecting after 5 seconds, and make it 60 if you want to redirect after 1 minute.
protected void btnRedirect_Click(object sender, EventArgs e)
{
Response.AddHeader("REFRESH", "5;URL=YourNextPage.aspx");
}
This code you can also put in Load event of the page so that it'll redirect to another page after loading current page.
You cannot use C# code to redirect after a certain time from the server side, since C# is executed on server side. You can do this by having the meta tag in your HTML:
<meta http-equiv="refresh" content="300; url=newlocation">
You can write code in C# to create this tag, Here is an example:
HtmlMeta meta = new HtmlMeta();
HtmlHead head = (HtmlHead)Page.Header;
meta.HttpEquiv= "refresh";
meta.Content = "300; url=newlocation";
head.Controls.Add(meta);
you can do so using:
System.Threading.Thread.Wait(60);
Response.Redirect("Somepage.aspx");
Edit:
System.Threading.Thread.SpinWait(60);
Response.Redirect("Somepage.aspx");
Note: The SpinWait parameter is a cycle count and not seconds as the above suggests.
Taken from MSDN page http://msdn.microsoft.com/en-us/library/system.threading.thread.spinwait.aspx
The SpinWait method is useful for implementing locks. Classes in the .NET Framework, such as Monitor and ReaderWriterLock, use this method internally. SpinWait essentially puts the processor into a very tight loop, with the loop count specified by the iterations parameter. The duration of the wait therefore depends on the speed of the processor.
There are many ways to do this but I love to use this code because it works well when used in many different circumstances.
HtmlMeta oScript = new HtmlMeta();
oScript.Attributes.Add("http-equiv", "REFRESH");
oScript.Attributes.Add("content", "60; url='http://www.myurl.com/'");
Page.Header.Controls.Add(oScript);
Doing this on the client would be better than doing it on the server.
You'll need to use javascript to setup a timer and then redirect.
See this on how to redirect:
How to redirect to another webpage in JavaScript/jQuery?
See this for timers:
Loop timer in javascript
http://www.w3schools.com/js/js_timing.asp
http://www.elated.com/articles/javascript-timers-with-settimeout-and-setinterval/
I love doing my stuff in JavaScript :-) I love JS. Here is my JS solution .
<script type="text/javascript"><!--
setTimeout('Redirect()',4000);
function Redirect()
{
location.href = 'your-redirect-to-link';
}
// --></script>
The page will be redirected after 4 minutes. You have to insert that into the head obviously.
I need to refresh sections of my page to update when there is new data! what do i do? use jquery?
examples:
Yes, jQuery's great for this. Look into these methods:
http://api.jquery.com/category/ajax/
jQuery is usually not needed for basic AJAX. A simple example could be as follows:
liveSection = document.getElementById('latest-news');
request = new XMLHttpRequest;
request.open('GET', '/news-ajax', true);
request.send(null);
request.addEventListener('readystatechange', function() {
if (request.readyState == 4 && request.status == 200)
liveSection.innerHTML = request.responseText;
}, false);
If you're using Asp.NET, why not use an UpdatePanel? It's simple and reliable.
Edit
I just re-read your question and it looks (based on how you worded it) that you want to update a user's web page when the data changes on the server. I just want to make sure you understand that in a web app, the server can't trigger the browser to do anything. The server can only respond to browser requests, so you'll need to have the browser poll the server periodically.
I've created a simple example (using jQuery) to help you understand the breakdown of the things that will need to happen, which are:
1 - Periodically polling the server (via ajax) using Javascript's setTimeout to check that what is loaded into the browser is the latest content. We can achieve this by fetching the latest item ID or whatever and comparing it to a variable, which was initialised when the page first loaded.
2 - If the item ID does not match (a bit of an oversimplification) then we can assume that there has been an update, so we replace the content of some element with some content from some page.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script>
function getLatestStuff() {
// fetch the output from a context which gives us the latest id
$.get("isthereanupdate.aspx", function(response) {
// we have the response, now compare to the stored value
if(resp != lastItemId) {
// it's different, so update the variable and grab the latest content
lastItemId = response;
$("#latestStuffDiv").load("updates.aspx");
}
});
}
$(document).ready(function() {
// the value which initializes this comes from the server
var lastItemId = 7;
setTimeout(getLatestStuff, 10000);
});
</script>
If you want to update when there is new data, you should look into comet or pubsubhubbub. jQuery can help you display the data in a pretty way, but you'll need to write stuff on the serverside to send the data.