I have a button on my webform. Clicking this button will do an HttpWebRequest during the onclick event handler. After the request we copy the response from the request into HttpContext.Current.Response and send that to the client.
This web request can take a while (up to 5 seconds, since it's generating a report). During this time the user has no indication that anything is going on, except for the browser progress bar and the spinning IE icon (if they're using IE). So I need a loading indicator while this is happening.
I've tried using javascript that fires during the button's onclick event (using OnClientClick) and while that works, I don't know how to find out when the web request is finished. Since we just send the response to the client, a full postback doesn't happen.
I've tried wrapping the button in an UpdatePanel and using the UpdateProgress, but when we send the response to HttpContext.Current.Response and call Response.End(), we get an error in the javascript, since the response isn't well formed (we're sending back an excel sheet for the user to download).
Since we're sending back a file for users to download, I don't want to pop-up a separate window, since then in IE they'd get the information bar blocking the download.
Any ideas here?
As an alternative to the Professional AJAX.NET library, jQuery has a really nice way of doing this.
Take a look at this example of using a .NET PageMethod (if possible in your scenario).
You define a page method call in jQuery, you can tack on your loading... message in a hidden div.
Say what callback you want to return on success (ie when your 5 second report is generated)
then hide the loading and handle the data.
Take a look at the javascript on my contact page for an example (view the source).
I have a a button on the page, add the jQuery onClick.
When clicked that shows a hidden loading div, makes an ajax call to a page method that takes the parameters of the form.
The page method does emailing etc then returns to the form in the onSuccess javascript method I have there.
The onSuccess hides the loading div.
A simple trick i have used in the past is to redirect to an intermediate page with an animated progress bar (gif) and then have that page do the REAL post of the data.
(or even pop-up a layer with the animation on it and a polite message asking the user to wait a minute or two)
The simple feedback of the animated gif creates the illusion to the end user that the app is not stalled and they will be more patient.
Another approach is to hand the data off to a worker thread and return immediately with a message stating that the report will be emailed or made available in the "reports" section of the site when it is ready. This approach lacks the benefit of instant notification when the report is completed though.
Here is my solution :
Download and examine the samples of free Professional AJAX.NET library.
Write a AjaxMethod that creates your file and returns file location as a parameter.
Write your Client-Side function to call method at Step 2. When this method called show an indicator.
Write a client-side callback method to hide indicator and show/download file that user requested.
Add your client-side function calls yo your button element.
When your method at server-side ends your callback will be called.
Hope this helps !
The solution I'm presenting here is aimed to show a method to let a "Loading..." box to appear while you're server-side processing and to disappear when server-side processing is complete.
I'll do this with the very basic AJAX machinery (tested on FF, but IE should be ok either), i.e. not using a framework like Prototype or jQuery or Dojo, as you didn't specify your knowledge about them.
To let you better understand the trick, the following is just a small example and doesn't pretend to be an out-of-the-box solution. I tend not to be superficial, but I think a clearer example can explain better than many words.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>First Example</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<style>
.hidden {
display: none;
}
.loadingInProgress {
color: #FFFFFF;
width: 75px;
background-color: #FF0000;
}
</style>
<script type="text/javascript">
var httpRequest;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
httpRequest = new XMLHttpRequest();
httpRequest.overrideMimeType('text/xml');
} else if (window.ActiveXObject) { // IE
try {
httpRequest = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
httpRequest = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {}
}
}
if (!httpRequest) {
alert('Giving up :( Cannot create an XMLHTTP instance');
}
httpRequest.onreadystatechange = function(){
switch (httpRequest.readyState) {
case 1: // Loading
document.getElementById('loading').className = "loadingInProgress";
break;
case 4: // Complete
document.getElementById('loading').className = "hidden";
if (httpRequest.status == 200) {
// perfect!
} else {
// there was a problem with the request,
// for example the response may be a 404 (Not Found)
// or 500 (Internal Server Error) response codes
}
break;
}
};
function go() {
httpRequest.open('GET', document.getElementById('form1').action, true);
httpRequest.send('');
}
</script>
</head>
<body>
<div id="loading" class="hidden">Loading...</div>
<form id="form1" name="form1" action="doSomething.php">
<input type="button" value="Click to submit:" onclick="go()" />
</form>
</body>
</html>
As you can see, there's a <div> which holds the "Loading..." message.
The principle is to show/hide the <div> depending on the XMLHttpRequest object's readyState.
I've used the onreadystatechange handler of the XMLHttpRequest to trigger the readyState change.
The back-end php script I use (declared as the form's action) does just a sleep(5), to let the "Loading..." message appear for 5 secs.
<?php
sleep(5);
header('Cache-Control: no-cache');
echo "OK";
?>
The Cache-control: no-cache header is necessary, since usually if you don't set it the browser will cache the response avoiding to resubmit the request if you should need to.
A good source for "getting started" AJAX documentation is Mozilla MDC.
The whole thing could be much more gently handled by a Javascript framework like Prototype, taking advantage of its browser-safe approach, saving you hours of debug.
Edit:
I chose php 'cause I don't know ASP.NET nor ASP, sorry about that.
Related
In my metro app ..I am using iframe to load a web application - basically a form which contains some controls and finally user click on finish button and i want to show alert
i know in metro app. we can give the alert using "new Windows.UI.PopupMessage" to show the alert. but how can i do the same from the web context(Iframe).
i have a function (showalert();) in my default.js where i am using the "new Windows.UI.PopupMessage" to show messages. if i am trying to access this function from iframe page like "window.parent.showalert();". i get exception saying access denied.
Please someone reply to this as this is very critical for me.
thanks & regards
Goutham
You can use HTML 5's postMessage to communicate between contexts.
Below is an image of a simplistic example with the relevant code snippets following it; the Bing Maps trip optimizer example uses this same technique on a grander scale.
The main page (default.js), which is running in the local context, includes an IFRAME loaded in web context via the following markup (I left out the unchanged <head> element to save space):
<body onload="localContext.onLoad();">
<p style="margin-top: 150px">This is default.html in the local context</p>
<div style="background-color: azure; width: 300px">
<iframe src="ms-appx-web:///webpage.html" />
</div>
</body>
localContext is defined in default.js as
var localContext = {
onLoad: function () {
window.attachEvent("onmessage",
function (msg) {
if (msg.origin == "ms-appx-web://bfddc371-2040-4560-a61a-ec479ed996b0")
new Windows.UI.Popups.MessageDialog(msg.origin).showAsync().then();
});
}
};
and it defines an onLoad function for default.html that registers a listener to the onmessage event, and when that event fires a MessageDialog is shown (or you can take whatever action you want to do in the local context).
Note that the parameter to the message event callback (msg here) also includes a origin property that you can check to make sure you're only handling messages from expected senders.
The web page hosted in the IFRAME calls postMessage in the onclick event handler of a button (you'll probably want to pull the invocation a separate .js file versus in-line)
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
This is webpage.html loaded into an iFrame
<button id="button" onclick="window.parent.postMessage('Hello from Web Context', '*');">Say Hello</button>
</body>
</html>
I have a web application that creates a graph on another aspx page. Sometimes the graph cannot be created to specification because there is an error in the user specification (such as a string where an integer was expected).
I would like to immediately pop up an alert window telling them that something went wrong when I was trying to render the graph.
The thing is, I don't know how to immediately check to see if I should insert a script for an alert window. Once my code on "chart.aspx"(image URL) is executed, I don't know how to immediately check if anything went wrong from the main page. I know it happened in the code in chart.aspx, but other than not to not render the image or render a different image, I don't know how to tell the user before another postback. I would really like to see if there is any sort or event or stage in the page lifecycle after one of the images is rendered.
If this is not possible, how can I chart.aspx convey an error message to default.aspx if it is simply an image. Maybe some sort of Response.Write(...?)
Thanks again guys.
Maybe you could try monitoring the image's load events and handle onabort and onerror via javascript?
http://www.w3schools.com/jsref/dom_obj_image.asp
Image Object Events
Event The event occurs when...
onabort Loading of an image is interrupted
onerror An error occurs when loading an image
onload An image is finished loading
The old school way of doing this would be to render your image tag like below:
<img src="chart.aspx" onerror="alert('Image failed to load because XYZ.');" />
Nowadays, I'd recommend you use jquery, something like this:
<img src="placeholder.gif" class="chart" alt="chart">
<script type="text/javascript">
jQuery(function($) {
var img = $(document.createElement('img'));
img.on('error', function() { alert ('...'); });
img.on('load', function() { $('img.chart').attr('src', img[0].src); });
});
I have a JavaScript class that displays a partially-opaque div over top of the content of another div when an Ajax request is sent to the server.
When the request returns, the JavaScript class hides the partially-opaque div....it works great...sort of.
Right now, in IE9, when the Ajax request is complete, the partial-opacity is only hidden if the user moves their mouse.
So, my question is, how do I force the browser to do what it's supposed to do?
This is my extremely simple function that is called after the request returns to the browser:
_hideBlockingDiv: function() {
if (this.get_blockingDivClientID()) {
var blockingElement = $get(this.get_blockingDivClientID());
if (blockingElement != null) {
blockingElement.style.display = 'none';
//I know that this method is executing correctly because I "hi" showed
//up properly...but the element remained visible:
blockingElement.innerHTML = 'hi';
}
//if I add the alert then everything works fine in IE9
//if I don't then the page will remain the same until the user moves their mose
//alert("done");
}
}
Please note that I am not using JQuery.
I am using the AJAX.NET library since I am a .NET developer (and JQuery didn't become popular until years after I implemented my Ajax-enabled server controls)
Thanks
-Frinny
How and where do you call the _hideBlockingDiv function from? Since you are using MS Ajax library, you might want to have a page loaded handler on client side and call this function from within that handler. So basically
Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function(){
_hideBlockingDiv();
});
Hope this helps!
It turns out that the problem only exists in the beta version of IE9 that I was using at the time. This problem went away once the full version of IE9 was released.
when my application launches in the IE from start page to main page i want to hide the addressbar and the standardbuttons bar of IE through the codebehind and here am using masterpage concept so i have to write the code in master only i think so....can anyone help for this
AFAIK you cannot disable address bar and button in IE from when the application starts unless using some ActiveX, Flash, ... Only if your application opens new window popups you could hide them.
I just found a way... It works atleast in IE 7... Not sure about other browsers...
<html>
<head>
<script>
if (window.name == 'default') {
window.name = 'Hai';
window.open('main.html', '_self'); // Current html file name
}
else if(window.name == '') {
window.name = 'Hai';
window.open('main.html', '_self'); // Current html file name
}
else if(window.name == 'Hai') {
// Use your application startup page here along with the desired options
window.open('newfile.aspx','NEWWINDOWNAME', 'Status=0, location=0');
window.close();
}
</script>
</head>
<body>
This window automatically closes itself
</body>
</html>
The complete list of options are available here.
Hope this helps.
Explanation : (AFAIK) Generally when javascript uses window.close method to close the active window, IE will ask for a confirmation from the user. Such confirmation will not be asked when the window is a popup window opened previously by a javascript along with a name.
The above just fakes the same, by opening the same file in the same window but this time with a name. As a result when window.close is executed, IE recognises the current window as a window opened using Javascript and as it also has a name, it just closes the same without confirmation.
Of course, I get a general Javascript alert at the beginning of the load, but since (I presume) you will be using aspx or other types, this problem will not be there.
just need tips on how to make forms where request are submitted via AJAX with a loading progress image. I am using update panels with AJAX framework. I would like to know about the recommended approach. Through JQuery or AJAX toolkit ?
Please advice, examples would be an added bonus for me.
1- Prepare a client side div with "display:none" style property. put your loading image inside.
2 - when the user or page submits a request, change that divs display property to "block".
3- Add some kind of "information received" sign to the response and check this response from the client side and then change that divs display property back to "none"
I would like to know about the
recommended approach
Well, that depends on what you are doing, what parts of the form are you updating, how big is the form, what values are you sending to the server.
Generally speaking, if you want to update something simple (dropdownlist, listbox, etc), youd generally use JavaScript (or jQuery) to call an AJAX-enabled web service. This way, you're only sending to the server the data it needs, things like ViewState/cookies are not sent over the wire. You also have full control over the pre/post execution events (so you can add your loading images, call the WS, then clear them).
However, if you want to asynchronously update an entire form (which has a lot of controls), you're probably right in using an UpdatePanel. Things like a GridView are a good case for an UpdatePanel (as you usually need to handle editing, binding and paging all asynchronously).
The progress image is made easy with the following code:
<ProgressTemplate>
<img src="someloadingimage.gif" alt="Loading" />
</ProgressTemplate>
Stick that inside your UpdatePanel, and whenever an AJAX call is made, the loading image will be shown.
HTH
If you use JQuery for AJAX request then you can use the following events -
$.ajax({ url: "test.html",
type: "GET",
beforeSend: function(){
-----load your loader here-----
});,
success: function(){
------remove your loader here -----------
Remaining code
}});
You can also use POST. in above example i have used GET.
For detailed documentation you can refer - http://api.jquery.com/jQuery.ajax/
Create a small plug-in for your loader like so.
$.fn.ShowLoader = function(on){
switch(on)
{
case true:
$(this).show();
break;
default:
$(this).hide();
break;
}
}
then use the following:
$('form').submit(function(){
var Form = $(this);
$('.loader',Form).ShowLoader(true);
//Gather some params
Location = Form.attr('src');
Data = Form.Serialize();
$.post(Location,Data,function(result){
result = result || false;
if(result)
{
$('.loader',Form).ShowLoader(false); //Disable the loader
//Process result
}
});
})
html would just be a regular form, with an image / div inside with the class of loader