Timer with javascript and C# - c#

I need to create a timer in an ASP.NET web page.
I have tested some JavaScript code like:
window.onload = function WindowLoad(event) {
setTimeout(function () { alert("DoIT") }, 60000);
}
and it works like expected but when I replace the alert with a call to a C# function like:
window.onload = function WindowLoad(event) {
setTimeout(function () { <% doIt(); %> }, 60000);
}
the function works on the load of the page and not after the specified period.

<% doIt() %> runs during the server side process, not on client. If you want to do something on the server side you should create a webmethod and make a post to it.

Try this blog post, this should be what you are looking for: http://deebujacob.blogspot.com/2012/01/aspnet-ajax-web-method-call-using.html
It's like other people sad you can not call server side functions directly from javascript you have to make a request, that's is way good God gave as ajax :)

Related

How do I inject javascript code via webview?

Basically what I want to do is this this but I can't seem to find something similar for webview XAML control. What I ultimately need to do, is capture an incoming json file from the webview. As is, I get a bad request from the server and unsupported file exception from the webview. I thought about injecting a javascript so that it would alert me, I could get the body of the incoming json and bypass all the errors.
There are two main things you can do:
Call functions programically
Inject any code by using the HTML string
Function Calling
You can use InvokeScript to call javascript functions.
If you have in a webpage with a script:
<script lang="en-us" type="text/javascript">
function myFunction() {
alert("I am an alert box!");
}
</script>
Then you can in C# call:
MyWebview.InvokeScript("myFunction", null);
Which will execute the script function myFunction.
Injecting Text
If you download the HTML page and all other needed files(using the Windows HttpClient), you can inject any code by manipulating and then Navigating to string.
Lets say you want to change the above script to add another function, "HelloWorld", then you can
Search the file for something you know will be there, such as: <script lang=\"en-us\" type=\"text/javascript\">
Using string manipulation, add the desired text, such as a function (but this can be anything)
Navigate to the String
The C# code:
string MyWebPageString = GetWebpageString(WebpageUri);
string ScriptTagString = "<script lang=\"en-us\" type=\"text/javascript\">";
int IndexOfScriptTag = MyWebPageString.IndexOf(ScriptTagString);
int LengthOfScriptTag = ScriptTagString.Length;
string InsertionScriptString = "function SayHelloWorld() { window.external.notify(\"Hello World!\");} ";
MyWebPageString = MyWebPageString.Insert(IndexOfScriptTag + LengthOfScriptTag + 1, InsertionScriptString);
MyWebview.NavigateToString(MyWebPageString);
The result will be that the navigated to Webpage will look like this:
<script lang="en-us" type="text/javascript"> function SayHelloWorld() { window.external.notify("Hello World!");}
function myFunction() {
alert("I am an alert box!");
}
</script>
Since the injection can be applied to any area, even the HTML, you should be able to figure something out.
Hope this helps. Good luck.
This answer was based on this MSDN blog

Detect ajax submit

I need to run a specific javascript function only when the page is submitted using ajax.
I've tried the following:
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"scriptName", "MyFunction();");
But it seems to run during normal post-backs as well. I've also tried replacing the Page object with the UpdatePanel control but without any difference.
Is it perhaps possible inside the javascript function MyFunction() to detect if it is an ajax or normal submit?
You can utilize Sys.WebForm.PageRequestManager two events
1) add_initializeRequest --> When an ajax post back is initiated
2) add_endRequest --> when an ajax post back is finished.
PageRequestManager also provides a function "get_isInAsyncPostBack()" which tells that if page is still in process of an existing ajax postback.
Example:
Sys.WebForms.PageRequestManager.getInstance().add_initializeRequest(function () {
var prm = Sys.WebForms.PageRequestManager.getInstance();
// Only one async request at a time
if (prm.get_isInAsyncPostBack()) {
prm.abortPostBack();
}
//Call the function or process you want to perform on ajax request begin
});
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(function () {
//Call the fucntion or process you want to perform on ajax request end
});
Any question, feel free to ask
This code solved the problem. Thanks to #user1341446 for pointing me in the right direction.
Register the javascript function on submit:
ScriptManager.RegisterOnSubmitStatement(Page, Page.GetType(),
"scriptName", "MyFunction();");
Inside the function detect if ajax submit:
function MyFunction()
{
var isAjaxSubmit = false;
if (typeof (Sys) != "undefined")
isAjaxSubmit =
Sys.WebForms.PageRequestManager.getInstance()._postBackSettings.async;
}

How to execute javascript in specifci time in .cs?

If i have script like this :
<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>
and i wanna to execute this script in specific time in my .cs code how to do this?
string rowTestHide = #"<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&
border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>";
ClientScript.RegisterStartupScript(this.GetType(),"rowTest", rowTestHide);
Try out with following code,
Page.ClientScript.RegisterClientScriptInclude("MyScript", "<script type="text/javascript" src="//www.gmodules.com/ig/ifr?url=http://hosting.gmodules.com/ig/gadgets/file/100080069921643878012/facebook.xml&up_useNewFB_p=1&up_showPopUp2_p=true&synd=open&w=320&h=500&title=Facebook&border=%23ffffff%7C3px%2C1px+solid+%23999999&output=js"></script>");
The only real way to do this at the moment (without using something like SignalR) is to implement a polling system.
You will have to have an Ajax call, that makes a request to your server every xxx seconds, using something like:
window.setTimeout(function(){ /* do ajax request */ }, 5000);
Which would run every 5 seconds.
If the desired result comes back from the DB, you'll have to then programatically inject the required script block into your page.
take a look at this:
jQuery AJAX polling for JSON response, handling based on AJAX result or JSON content

Load .NET Resources Client-Side on each request

I have the following JavaScript snippet:
<script type="text/javascript">
var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_beginRequest(ajaxBeginRequest);
prm.add_endRequest(ajaxEndRequest);
function ajaxBeginRequest(sender, args) {
$.blockUI({ message: '<h1><img src="/images/ajax_loading.gif" /> <%= MyNameSpace.SomeWhereElse.Shared.RandomLoadingMessage() %></h1>' });
}
function ajaxEndRequest(sender, args) {
$.unblockUI();
}
</script>
Right now the C# line runs at page load and gives me one random message, but it is constant through the page execution until the page is refreshed. What I'd like it to do is give me a different message on each ajax Request
Any suggestions for this?
You can make a ajax call to a web service (called script service) to get the message on each invocation. See this article where it explains how to call script services using ASP.NET generated proxies as well as using jquery methods. You can use either method.

jQuery "Microsoft JScript runtime error: Object expected"

I have the below code that does not seem to work at all :( I keep getting:
Microsoft JScript runtime error: Object expected
The error seems to occur when the timeout is done. So if I raise the timeout with 10 seconds the error holds for another 10 seconds.
I want to be able to update the number of friends online async. The number is shown with the following html:
(?)</strong>
The friends part is set at the first run, but when the timeout calls back it does not fire again. Also, I cannot see on which line the error occurs because if I want to break on the error it just shows "no source code" etc.
The code below is the code I'm using. Thanks!
<script src="http://ajax.microsoft.com/ajax/jquery/jquery-1.3.2.js" type="text/javascript"></script>
<script src='/Scripts/MicrosoftAjax.js' type="text/javascript"></script>
<script src='/Scripts/MicrosoftMvcAjax.js' type="text/javascript"></script>
<script src='/Scripts/jquery.autocomplete.js' type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function() {
UpdateFriendsOnline();
function UpdateFriendsOnline() {
window.setTimeout("UpdateFriendsOnline()", 1000);
$.get("/Account/GetFriendsOnline", function(data) {
$("#friendsOnline").html("(" + data + ")");
});
}
});
</script>
Change your setTimeout() like this:
window.setTimeout(UpdateFriendsOnline, 1000);
Currently your function isn't available outside the document.ready, so it's not accessible as a global function, which passing it as a string is trying to access it as. As a general rule, never ever pass setTimeout() a string if you can avoid it...it can cause problems like this case, and I can't think of an example (that if avoidable) is made better by it being a string.
Also, I suggest firing it when you get the response back, otherwise you'll start queuing up overlapping ajax requests, you can do that by adjusting your function to this:
function UpdateFriendsOnline() {
$.get("/Account/GetFriendsOnline", function(data) {
$("#friendsOnline").html("(" + data + ")");
window.setTimeout(UpdateFriendsOnline, 1000);
});
}
Try this:
window.setTimeout(UpdateFriendsOnline, 1000);
The version you had would have worked if the function was defined in the global namespace.
This way, you're passing in a local reference to the function, which will get called every second.
EDIT:
If you need to cancel the previous request before the new one starts, you can do something like this:
<script type="text/javascript">
$(document).ready(function() {
var request; // Stores XMLHTTPRequest object
UpdateFriendsOnline();
function UpdateFriendsOnline() {
if(request) request.abort(); // Abort current request if there is one
window.setTimeout(UpdateFriendsOnline, 1000);
// Store new XMLHTTPRequest object
request = $.get("/Account/GetFriendsOnline", function(data) {
request = null; // Clear request object upon success
$("#friendsOnline").html("(" + data + ")");
});
}
});
</script>

Categories