I am trying to reload a page every 10 seconds , using Cache Scheduler method mentioned here,
I just want call a JavaScript function to reload current page when Cache is removed. But for some reason basic JavaScript doesn't work.
Razor View:
#{
AddTask("CheckStatus", 10); // reload page every 10 seconds
#functions
{
private static System.Web.Caching.CacheItemRemovedCallback OnCacheRemove = null;
public void AddTask(string name, int seconds)
{
OnCacheRemove = new System.Web.Caching.CacheItemRemovedCallback(CacheItemRemoved);
HttpRuntime.Cache.Insert(name, seconds, null,
DateTime.Now.AddSeconds(seconds), System.Web.Caching.Cache.NoSlidingExpiration,
System.Web.Caching.CacheItemPriority.NotRemovable, OnCacheRemove);
}
public void CacheItemRemoved(string k, object v,
System.Web.Caching.CacheItemRemovedReason r)
{
PrintStatus();
}
}
}
#helper PrintStatus()
{
var msg = "<script language='javascript' type='text/javascript'>
alert('Status is open!');</script>";
#Html.Raw(msg)
}
What am i doing wrong ? Or Is there any alternate way to return Javascript to reload page using server side code.
Note: I am not using Javascript set interval because Chrome has issues when the browser is minimized, so i prefer server side code to reload page every x seconds.
Any help would be great.
The cache scheduler is server-side piece of code. It is useless on client. The way this would fire is only if by some miracle the CacheRemoveItem will fire when you're rendering the view.
If I were you I'd create some AJAX service and periodically call it from javascript using setInterval.
Related
I have a gridview with a list of pdf files. When the user clicks a pdf, it displays the file inline on the page. I want to execute some javascript after the pdf has been loaded but I cannot get this to work. The issue is that the pdf loads after everything else, so the load event fires before the pdf begins to load.
My first approach was to use an iframe. The inner page would retrieve the file and write the data to the response. As mentioned previously, the load event occurred before loading the pdf and I need it to trigger after. The current code uses a generic handler ashx to load the pdf inline. How do I trigger an event to execute javascript, after the pdf data is loaded server side from the ashx generic handler?
Aspx page:
protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
if (e.CommandName == "View")
{
int index = Convert.ToInt32(e.CommandArgument.ToString());
string Id = GridView1.DataKeys[index].Value.ToString();
HtmlGenericControl myObject = new HtmlGenericControl();
myObject.TagName = "object";
Panel1.Controls.Add(myObject);
myObject.Attributes.Add("data", "GetPdf.ashx?Id=" + Id);
}
}
Generic handler ashx:
public void ProcessRequest(HttpContext context)
{
System.Diagnostics.Debug.WriteLine("GetPdf.ashx started");
string Id = context.Request.QueryString["Id"];
byte[] data = GetPdf(Id);
context.Response.ClearContent();
context.Response.ContentType = "application/pdf";
context.Response.AppendHeader("Content-disposition", "inline");
context.Response.AddHeader("Content-Length", data.Length.ToString());
context.Response.BinaryWrite(data);
System.Diagnostics.Debug.WriteLine("GetPdf.ashx is done");
context.Response.End();
}
Have you tried setting an event handler for the object tag's onload event? I'm not sure if that will work across all browsers, but I also don't know which browsers you require it to work on.
Worst-case scenario you could use setTimeout to rapidly poll for the PDF's existence.
Here's a previous answer that may help you with both aspects.
I'm limiting the amount of certain pop up windows with a static counter in the back-end of my web form application (C#). I only want to have 1 window open at a time. The back-end counter works fine, however when a user closes the child window I want to reset the counter in the back-end. For that I'm using AJAX with JS (can't use JQuery) and I'm calling that AJAX to make a POST in the back-end in an onUnload event.
I'm using IE 11.
Back-end method I want to call from my JavaScript.
public void DecreaseItem1()
{
int? inspID = convert.ToInt(Request.QueryString["inspid"]);
int? inpID_static = InspectionList.GetWindowInspID();
string path = HttpContext.Current.Request.Url.AbsolutePath;
if (path.Contains("ReadOnlyInspection"))
{
if (inspID != inpID_static)
{
InspectionList.DecreaseCounter();
}
else
{
InspectionList.DecreaseCounter();
InspectionList.SetGetWindowInspID(null);
}
}
From my front-end I'm calling onUnload the DecreaseItem() JavaScript function.
Body tag
<body onUnload="DecreaseItem()" >
JavaScript function:
<script type="text/javascript">
function DecreaseItem() {
var win_loc = "ReadOnlyInspection.aspx/DecreaseItem1";
var xhttp = new XMLHttpRequest();
xhttp.open("POST", win_loc, true);
xhttp.send();
}
</script>
[problem] Counter never gets decreased. Any help or suggestion is greatly appreciated.
I am noob to ASP.net.
I was trying to add a confirmation popup to webpage.
I used the following code :
(which is a variant from this one: http://www.codeproject.com/Articles/8173/A-Simple-ASP-NET-Server-Control-Message-Box-Confir )
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.ComponentModel;
using System.Text;
namespace BunnyBear
{
[DefaultProperty("Text"),
ToolboxData("<{0}:msgBox runat=server></{0}:msgBox>")]
public class msgBox : System.Web.UI.WebControls.WebControl
{
//private string msg;
private string content;
[Bindable(true),
Category("Appearance"),
DefaultValue("")]
public void confirm2(string msg)
{
string sMsg = msg.Replace("\n", "\\n");
sMsg = msg.Replace("\"", "'");
StringBuilder sb = new StringBuilder();
sb.Append(#"<script language='javascript'>");
sb.Append(#" if(confirm( """ + sMsg + #""" ))");
sb.Append(#" { }");
sb.Append(#" else { ");
sb.Append( "document.forms[0].submit(); }");
sb.Append(#"</script>");
content = sb.ToString();
}
protected override void Render(HtmlTextWriter output)
{
output.Write(this.content);
}
}
}
I try it from a test class as follows :
//event triggered when clicking a button
protected void Button2_Click(object sender, EventArgs e)
{
msgBox1.confirm2("are you sure?");
MoreCode();
}
I was expecting that when I click on the button, the confirmation popup pops and asks if I want to confirm:
if I click "no" : postback occurs so MoreCode() is not executed
If I click "yes" : no javascript code is executed, so the execution goes on and MoreCode() is executed.
This is not what happens.
When I click the button with the step by step debugger, I can see that :
it executes msgBox1.confirm2("are you sure?");
it then executes MoreCode()
and afterwards the popup pops
Could you pls explain me why this is executed in this order?
Thanks in advance.
MoreCode() is running on the server side, whereas the popup is on the client side. They are independent operations. If MoreCode must run after the button click, then you need to have a callback in your JavaScript, appending it after
sb.Append(#" if(confirm( """ + sMsg + #""" ))");
The callback would bind to a server call, and that server call would execute MoreCode.
Since you are not using any AJAX, the order of operations is clear: all server-side code is run, then HTML is returned to the browser where the browser executes any necessary client-side code. Here is what happens, in order, starting from when your Button2 is clicked:
Button2_Click server event is called. This event does everything it is asked to do: create a string that will be injected to the resulting HTML page, and then run MoreCode(). Control has not yet been returned to the browser--all this processing is handled on the server-side.
HTML for the resulting page is rendered, along with the string you injected, which includes the JavaScript you have written.
HTML is transferred to the browser and the HTML is executed. Your script triggers a JavaScript prompt, which is then displayed to the user using the text that was specified server-side.
I'm trying to write KDE4 plasmoid in JavaScript, but have not success.
So, I need to get some data via HTTP and display it in Label. That's working well, but I need regular refresh (once in 10 seconds), it's not working.
My code:
inLabel = new Label();
var timer= new QTimer();
var job=0;
var fileContent="";
function onData(job, data){
if(data.length > 0){
var content = new String(data.valueOf());
fileContent += content;
}
}
function onFinished(job) {
inLabel.text=fileContent;
}
plasmoid.sizeChanged=function()
{
plasmoid.update();
}
timer.timeout.connect(getData);
timer.singleShot=false;
getData();
timer.start(10000);
function getData()
{
fileContent="";
job = plasmoid.getUrl("http://192.168.0.10/script.cgi");
job.data.connect(onData);
job.finished.connect(onFinished);
plasmoid.update();
}
It gets script once and does not refresh it after 10 seconds. Where is my mistake?
It is working just fine in here at least (running a recent build from git master), getData() is being called as expected. Can you see any errors in the console?
EDIT: The problem was that getUrl() explicitly sets NoReload for KIO::get() which causes it load data from cache instead of forcing a reload from the server. Solution was to add a query parameter to the URL in order to make it force reload it.
I'm currently programming in JSP and Javascript. (I am by no means an expert in either). Right now, what I want is for a Javascript function to be called repeatedly and one of the variables to be queried from the database repeatedly (it is the date that the page was last modified). If this variable is greater than when the page was loaded, I want the page to refresh.
What I have so far:
...
<body onload="Javascript:refreshMethod()">
<script type="text/JavaScript">
<!--
function refreshMethod()
{
var interval = setInterval("timedRefresh()", 10000);
}
function timedRefresh() {
var currenttime = '<%=currentTime%>';
var feedlastmodified = '<%=EventManager.getFeedLastModified(eventID)%>';
var currenttimeint = parseInt(currenttime);
var feedlastmodifiedint = parseInt(feedlastmodified);
if(feedlastmodifiedint > currenttimeint)
{
alert(feedlastmodifiedint);
setTimeout("location.reload(true);",timeoutPeriod);
}
if(feedlastmodifiedint < currenttimeint)
{
alert(feedlastmodifiedint + " : " + currenttimeint);
}
}
// -->
</script>
The problem is that everytime the timedRefresh runs, the feedlastModifiedInt never changes (even if it has been changed).
Any help would be appreciated,
Thanks.
The JSP code within the <% ... %> tags runs only once, on the server-side, when the page is loaded. If you look at the source of the page in the browser, you will find that these values have already been placed within the JavaScript code, and thus they will not change during each timer interval.
To update the data as you are expecting, you can use AJAX. You can find plenty of tutorials online.
JSP and JavaScript doesn't run in sync as you seem to expect from the coding. JSP runs at webserver, produces a bunch of characters which should continue as HTML/CSS/JS and the webserver sends it as a HTTP response to the webbrowser as response to a HTTP request initiated by the webbrowser. Finally HTML/CSS/JS runs at the webbrowser.
If you rightclick the page in webbrowser and choose View Source, you'll probably understand what I mean. There's no single line of Java/JSP code. It has already done its job of generating the HTML/CSS/JS. The only communication way between Java/JSP and JavaScript is HTTP.
You need to move this job to some servlet in the server side and let JS invoke this asynchronously ("in the background"). This is also known as "Ajax". Here's a kickoff example with a little help of jQuery.
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
$(document).ready(function() {
var refreshInterval = setInterval(function() {
$.getJSON('refreshServlet', function(refresh) {
if (refresh) {
clearInterval(refreshInterval);
location.reload(true);
}
});
}, 10000);
});
</script>
Where the doGet() method of the servlet which is mapped on an url-pattern of /refreshServlet roughly look like this:
response.setContentType("application/json");
if (EventManager.getFeedLastModified(eventID) > currentTime) {
response.getWriter().write("true");
} else {
response.getWriter().write("false");
}
See also:
Communication between Java/JSP/JSF and JavaScript