I'm new to programming with servlets and ajax. I have client side code that I use to track mouse actions over an image. I need to send the coordinates during a drag to the servlet for processing. I use ajax for this. I have the code working but there seems to be a lag in processing the requests in the servlet. Specifically with dragging.
Client Side Code:
$(document).ready(function(){
// detect mousedown
$("#imgslot").mousedown(function(event){
var leftClick = false; // if user clicked the left mouse button
var rightClick = false; // if user clicked the right mouse button
var interaction={type:"",action:"",lClick:"",rClick:"",x:"null",y:""};
//if the client left clicks
if(event.which===1){
leftClick=true;
}
//if the client left clicks
if(event.which===3){
rightClick=true;
}
interaction={type:"interaction",action:"mousedown",lClick:leftClick,rClick:rightClick,x:event.clientX,y:event.clientY};
sendAjax(interaction);
// detect dragging
$(this).on('mousemove',function(event){
interaction={type:"interaction",action:"drag",lClick:leftClick,rClick:rightClick,x:event.clientX,y:event.clientY};
sendAjax(interaction);
// detect mouseup
}).mouseup(function(event){
interaction={type:"interaction",action:"mouseup",lClick:leftClick,rclick:rightClick,x:event.clientX,y:event.clientY};
sendAjax(interaction);
rightClick = false;
leftClick = false;
$(this).off('mousemove');
$(this).off('mouseup');
});
});
});
function sendAjax(message)
{
$.ajax({
url: "myServlet",
type: "POST",
data: message,
success: function (data) {
}
});
}
In Servlet: Simply printing the requests to test the performance
if (request.getParameter("type") != null) {
System.out.println(request.getParameter("action"));
if (request.getParameter("type").equals("interaction")) {
sendMouseActions(request.getParameter("action"), request.getParameter("lClick"), request.getParameter("rClick"), request.getParameter("x"), request.getParameter("y"));
}
}
My biggest issue is that on a drag, because I have to send each coordinate, when I view my output, it continues to print out that I'm dragging even after I stopped the drag operation. This lag continues for sometime. Any advice?
Of course that will have bad performance. You should handle mouse movement stuff in javascript on the client side. For drag and drop send servlet only begin and final end position. Ajax requests are asynchronous, so you'll end up getting the coordinates out of order anyway if you you send a request each time onmousemove is fired. That's probably why its telling you that you are still dragging after you stopped; requests are getting out of order.
Related
I am loading a report in an iframe using ReportViewerForMvc. Currently, I have a spinner so that the user will know the report is loading. However, the spinner stops spinning when the iframe is placed on the page...not when the content of the report is finished rendering. I have found people using isLoading with $find but I am pretty sure that is just for asp and I need my to be in .Net
What is the simplest way to have spinner continue to spin until the report is loaded in the iframe?
Currently, I have a shared view for all reports that I am hoping to add some javascript to:
#using ReportViewerForMvc;
<div id="reportViewer">#Html.ReportViewer(Model.ReportViewer as Microsoft.Reporting.WebForms.ReportViewer)</div>
iframe onload does not work to stop spinner here.You would need cookies and client side script to accomplish that.
The server code will set the value in the cookie .Once the report is rendered the value will be read on the client side(cshtml) and spinner can be stopped.
Read this article.Here you can replace the blocker with the spinner.
http://gruffcode.com/2010/10/28/detecting-the-file-download-dialog-in-the-browser/
//This should be called on the event when you are loading the report
//In your case you will route the url to controller or invoke the link
//for the report
$(document).ready(function () {
$('#create_pdf_form').submit(function () {
blockUIForDownload();
});
});
//This is where you will place the spinner
function blockUIForDownload() {
var token = new Date().getTime();
//use the current timestamp as the token value
$('#download_token_value_id').val(token);
$.blockUI();
fileDownloadCheckTimer = window.setInterval(function () {
var cookieValue = $.cookie('fileDownloadToken');
if (cookieValue == token)
finishDownload();
}, 1000);
}
//This will read the token generated from the server side controller or
//aspx.cs or ashx handler
function finishDownload() {
window.clearInterval(fileDownloadCheckTimer);
// $.removeCookie('fileDownloadToken'); //clears this cookie value
//$.cookie('fileDownloadToken', null);
//$.removeCookie("fileDownloadToken");
setCookie("fileDownloadToken", '2')
$.unblockUI();
}
//On the server side set the token , it could be controller or ashx handler
var response = HttpContext.Current.Response;
response.Clear();
response.AppendCookie(new HttpCookie("fileDownloadToken",
downloadTokenValue); //downloadTokenValue will have been provided in the
form submit via the hidden input field
response.Flush();
//Lastly don't forget to add these source js files.
<script src="~/Scripts/jquery-1.5.1.js"></script>
<script src="~/Scripts/jquery.blockUI.js"></script>
<script src="~/Scripts/jquery.cookie.js"></script>
I have a website with master page. I want to catch a user trying to close the browser/tab. When I try using onunload in the body tag, it fires not only when I try closing the browser, but also when I navigate to another page.
Any idea how to only catch the event of closing the browser?
You can't distinguish closing the browser from navigating to another page. In both cases the current page is unloaded.
update: maybe you can handle some cases with some jquery, i.e. whenever a link is clicked, set some flag to be able to distinguish it from closing the window or entering a new URL:
<body onunload="checkForClose()">
...
<script>
var _isNavigation = false;
$(document).ready(function () {
// whenever a link is clicked set _isNavigation to true
$('a').click(function () {
_isNavigation = true;
});
});
function checkForClose() {
// show an alert if _isNavigation is not set
if (!_isNavigation) alert("closing the browser (maybe)");
}
</script>
I have a webform and i want to detect if F5 button was pressed or if the page was refreshed. I know about postback but it is not what i'm looking for. I have a gridview that loads in a modal popup when a button is clicked and a parameter's value is set for the gridview. When refresh is hit and if the modal popup button was previously clicked the modal popup is visible right after refresh. I want to detect if the page is refreshed to prevent this. any ideas? I thought to try Override but I'm not exactly sure how to use it. I tried Control.ModifierKeys but I don't have access to ModifierKeys.
Pressing F5 or physically clicking the browser refresh behaves similarly to navigating away from the page. This is captured in the event window.onunload. Try the snippet example below:
window.onbeforeunload = function (evt) {
var message = 'Are you sure you want to leave?';
if (typeof evt == 'undefined') {
evt = window.event;
}
if (evt) {
evt.returnValue = message;
}
return message;
}
This will capture the refresh and allow you to do something or prompt the user.
Reemember that hotkeys are processed in the client side in the browser. The easiest way to implement this is through javascript.
Look at the following link:
http://snippets.dzone.com/posts/show/3552
Short Explanation:
I have a script control that has the click event being handled in the script file. The Click handler pops up a confirm prompt and returns the prompt's value.
Problem:
IE sees the return False (Cancel is selected on the confirm box) and there is no postback. Firefox ignores this and fires the postback.
Solution?:
I read that if I were doing this the old fashion way, I would need to have:
onClick="return SomeMethod();"
In the markup. There hopefully is a way to do this with script controls?
Example:
Here's what I have in the script file:
//THIS IS THE METHOD CLICK CALLS
handleLnkDeleteButtonClick: function(e)
{
var confirmed = confirm('This will delete the current Message category and move all messages to the Oprhan cataegory. Continue?');
return confirmed;
},
initialize: function()
{
this._lnkDeleteButton = $get(this._lnkDeleteButtonID);
this._lnkDeleteButton.idpicker = this;
//HOOK BEGINS HERE
this._lnkDeleteButtonClick = Function.createDelegate(this, this.handleLnkDeleteButtonClick);
$addHandler(this._lnkDeleteButton, "click", this._lnkDeleteButtonClick);
//END HOOK HERE
NDI.WebControls.Client.PersonalMessageTypePicker.callBaseMethod(this, 'initialize');
},
dispose: function()
{
$removeHandler(this._lnkDeleteButton, "click", this._lnkDeleteButtonClick);
NDI.WebControls.Client.PersonalMessageTypePicker.callBaseMethod(this, 'dispose');
}
Ok so solved it myself after about way too much time trying to phrase things correctly for google. Turns out there is a method to call so that you don't have to worry about returning true or false.
handleLnkDeleteButtonClick: function(e)
{
var confirmed = confirm('This will delete the currery Message category and move all messages to the Oprhan cataegory. Allow?');
if (!confirmed)
{
e.preventDefault();
}
},
So instead of returning confirmed, I merely had to check it's value and call the e.preventDefault method to stop the click from firing.
Is there a client event that I can use for when a DropDownList's data has been loaded/bound onto the control? I need to trigger event on their side when this happens.
Basically, I am trying to lock out the controls while the data is being loaded as if there is a slowdown (not uncommon) a user can start inputting data and then lose focus as they are typing.
I tried doing this in the tags but the methods located there seem to stop working after the first postback! (Any help there would be greatly appreciated). As a workaround I tried attaching the events to the elements themselves and while this works for locking, using the onchange event, I am unable to unlock it upon the data successfully loading!
Any ideas? Thanks for the answers so far :)
Since data will be bound on the server side, you don't have a client-side event for that specific event, however, one the page has rendered, the data will be there, so you may want to run your client script in the document.load event, or using something like jQuery's document.ready event. That will trigger your script to run once the page (including your bound drop down) is finished loading.
Jason is correct here in that you cannot "notify" the client when such an event occurs. One thing you could do, is call the Page.RegisterStartupScript() method to do something with JavaScript once the page has finished loading (and assumedly that the post back that has done your databinding has occurred). Again, this assumes that you want to do something on the client side once the data binding is complete, as opposed to server side.
Are you able to use ASP.NET AJAX in your application? If so, you can have the selected event open up a modal dialog in which you can display your "processing" text while you are populating the drop down list. That way the user does not have access to any other controls and you can do what you need without worry.
i use the following code in my master pages for my websites. This stops the user from attempting to use a control before its completely bound. I have found that if a control hasn't been completely bound (slow connections) then the page blows up.
Essentially the script hijacks the post back if that page isn't done. Allowing the user to not do anything until the page has finished processing. I wrote this a year ago and its come in very handy.
first set the onload body tag to setdopostback()
add this in a scrip block in the body.
var boolDoPostBack = false;
if (__doPostBack)
{
// save a reference to the original __doPostBack
var __oldDoPostBack = __doPostBack;
//replace __doPostBack with another function
__doPostBack = AlwaysFireBeforeFormSubmit;
}
function setdopostback()
{
boolDoPostBack = true;
}
function AlwaysFireBeforeFormSubmit (eventTarget, eventArgument)
{
var x= document.readyState
if (x != "complete")
{
if (x == "loading" || x == "interactive" || x == "unitialized" || x == "loaded")
{
//do nothing with IE postback
}
else if (!boolDoPostBack)
{
//do nothing with FireFox postback
}
else
{
//alert('Allow Postback 1');
return __oldDoPostBack (eventTarget, eventArgument);
}
}
else
{
//alert('Allow Postback 2');
return __oldDoPostBack (eventTarget, eventArgument);
}
}