I have an ASP.NET MVC3 application running in a factory intranet. Factory uses Internet Explorer and end users are a little bit impatient. In a page where I'm adding a new object to database, Explorer doesn't respond quickly and users re-press the add button, hence the same object is inserted twice. I'm thinking of ways to prevent it.
I've written a script that makes the button invisible after it's pressed, but I want to make it just not-working. Is there such a javascript function or a server-side implementation that makes submit button doesn't work?
"Not working" clientside:
I would say disabling
document.getElementById("btnAdd").disabled = true;
is a little more safe than just making it invisible. On top of that, consider adding a loading animation in the form of a GIF from http://www.ajaxload.info/ so that the user knows they have to wait.
Ideally, you'd be making ajax calls and could re-enable the button if the action failed or returns a message.
Worst case scenario, you could remove the button from the page altogether, but that's not a very good idea if the action fails and the user will need to press it again.
"Not working" serverside:
On the database level, catch and reject duplicates (to your criteria) to ensure that even if they do slip one past, you don't end up with duplicate data.
Related
Simplified: In my JS/PHP app I have a button. When a user clicks on the button he gets 1 point which is saved via jQuery AJAX/PHP in a database.
Of course the user now can call the script that makes the AJAX request without clicking the button. Is there any best-practice to avoid that?
I am using AJAx because I don't want the page to reload.
Update:
There are many other options how a user can earn points. Idealy I would have a JS function add_points(points) that adds the points for the user. But I know that anyone can write a script to call this function automaticly. I guess the only way is to generate a hash vor every possible point-earn action and submit this hash with the AJAX request.
One thing you could do is to generate a hash and check if that hash is new or no used in the last day for example.. making sure that the user has to get a new hash in order to press the button.
If the user is allowed to click as many times as she wants, there's no real way to prevent doing it automatically. If she's only supposed to click once (like upvoting on stackoverflow), the code your server uses to update the value should automatically confirm that she hasn't clicked it before i.e. check the database.
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
/* special ajax here */
die($content);
}
You need an audit trail to properly solve this problem
Set the status "user clicked the button" rather than "user gets 1 point", and calculate the user's score as the sum of all actions that assign points. That is the basic approach used by Stack Overflow.
That way, you have an accounting record of how user's got their points, and you can implement business rules like "only allow setting status user clicked the button once"
The way you currently do it, there is no audit trail and indeed you have no way of knowing why users have the score they do.
I have a requirement where clicking on an icon should open a new window where the user will be able to view and edit certain fields. After the user closes this window and comes back to parent window, the icon color and text should be changed( for eg:- if the user has removed certain data, the icon will change to red color and text is set to null. If the user presses cancel button, nothing changes)
I am planning to implement this using a body onload function which essentially checks with the database using AJAX requests to see if the user has changed the data, then accordingly change the icon and text.
But, I see 2 problems in this approach
1. There will be a AJAX call even if the user has not changed anything.(ie. pressed Cancel button)
2. AJAX is called every time the body is on focus. Eg:- He may be working on some other page (or a different browser altogether) and comes back to this, resulting in an AJAX call.
Can anybody suggest a better approach.
I am using Javacript, JSP, Java
Two ways to implement this
Method 1
You know the methods which changes the database in the opened form. Suppose you have a delete method, write an additional window.opener.location.reload() after the method. The downside is that opener(parent window) gets reloaded every time you change something in the child window. Which is unnecessary.
Method 2 - Using cookies
I am using MDN's A little framework: a complete cookies reader/writer with full unicode support for creating cookies. The plan of action will be this. Create a cookie and set a value for it like this after you change anything in the child window and update it in the database like this docCookies.setItem("isChildFormUpdated", "yes");. You can use the same cookie for every action you do. Now when you navigate back to the parent form, do this.
$(document).ready() {
$(window).focus(function () {
var formCookie = docCookies.getItem("isChildFormUpdated");
if (formCookie !== null && formCookie == "yes") {
//resetting the cookie. you can also remove the cookie
docCookies.setItem("isChildFormUpdated", "no");
//docCookies.removeItem("isChildFormUpdated");
// your ajax call comes here
//or you could simply reload the form so that we get fresh data
//window.location.reload(); // it will be heavier
}
});
});
I hope you get the basic idea.
I think the easiest way to do this would be to set a cookie (learn how here). You can then have the two windows communicate between each other. This wouldn't be AJAX, but it will most likely work.
Another nice way to create a popup-like box is by using a modal box. These can be complicated but they look very nice. You have to make a jQuery plugin in, but you can take the one here and learn how it works. Good luck with your requirement.
I am searching for a way to close a Javascript pop-up/message box (i.e. not a NEW IE window, but a scripted alert()) that loads when a webpage is loaded.
I currently have code that loads data into a search form, runs the search, retrieves the needed information from the results, exits the search, then continues with the next item in a list. In some cases, there is a piece of critical information missing from the search results. When this happens, the JavaScript on the page pops up the message when the page loads, letting the user know that info is missing. With the automation the code halts(waits) for the box to clear before continuing, and the user must click on the OK button before this will happen.
(I have no way to change the source script of the page directly, as that is outside of my scope of responsibility here at work. Plus, it is more important to retain this functionality for general use; it would really only benefit this small-usage function I'm creating.)
While I can't change the source script, I have found an example of how to prevent a pop-up/alert from displaying by changing the loaded script. However, it relates to an already-loaded page and doesn't really work for me (as far as I can tell).
IE.Document.getElementById("clearRelItems").removeAttribute "onClick"
IE.Document.getElementById("clearRelItems").setAttribute "onClick", "return true;"
Is it possible to use this method to make a change before the page has fully loaded? i.e. can this be used to somehow bypass/circumvent the function call at page load?
I know about sendkeys, but I would prefer to avoid this option if at all possible (I may end up using this option if no other alternative exists). This function is intended to be initiated by the user, then left running in the background as it will take some time to complete.
I have looked into grabbing the XML as suggested by #Kyle, but I don't believe I am proficient enough to make this method work.
How else might I get around the alert? Is there a way to actually activate the OK button on the alert? Can the alert/loading of the page be bypassed any other way?
One work-around could be to recognize when your script is stuck and then just send the keystroke "enter" to close the pop-up.
Have you had a look at using the MS XML classes for posting the data directly and parsing the result? This is much faster than IE automation although admittedly not always possible
Edit: Not really, we're just using the classes to handle the request and response, we don't actually use XML, I put this together for someone a while back to give you an idea:
Sub GetDataXML()
Dim strPostText As String, strResponse As String
Dim Pressure As Double, Temperature As Double
Dim XMLrequest As Object
Pressure = CDbl(InputBox("Enter the Pressure"))
Temperature = CDbl(InputBox("Enter the Temperature"))
strPostText = "lang=english&calc=standard&druck=" & Pressure & "&druckunit=1&temperatur=" & Temperature & "&tempunit=1&Submit=Calculate"
Set XMLrequest = CreateObject("MSXML2.XMLHTTP")
With XMLrequest
.Open "POST", "http://www.peacesoftware.de/einigewerte/calc_co2.php5", False
.setRequestHeader "Content-type", "application/x-www-form-urlencoded"
.send (strPostText)
Do: DoEvents: Loop Until .readyState = 4
strResponse = .responseText
.abort
End With
Debug.Print strResponse
End Sub
It is even easier if you are using a query table in excel as this handles any parsing of the data.
Does the above help you?
I am trying to figure out the best way to acompish "unobtrusive" forms for a user (within a web app).
The purpose: keep user on the site by not asking to fill unnecessary form in. Ask for the details as only when such are needed.
The requrements are:
User should provide additional details only when it is required (email to receive notifications, login required for account page, save credit card details when checking out).
User should not leave the current page providing the additional details.
The implementation would be fairly easy if all requests would be AJAX ones. It would be easy to analyse the response (401 or so) and show the appropriate lightbox-form.
I do not see how it can be done "the right way" with plain anchors and form submits as in both cases the user actually leaves the page (by following the link or submitting a form) and there is no way to analyse the response on the client side.
Converting all links and forms to AJAX ones would be just silly.
The closest analog to what I want to achieve is the default Basic Authentication dialog in most of the browser. But obviously that just doesn't fit my requirements.
Any creative suggestions how to do that for non-AJAX requests?
Regards,
Dmytrii.
In a page sense, where "page" refers to what the user sees and not what the URL is, I only can think of following ways to update independent parts in a page with JavaScript (and thus Ajax) switched off:
Frames
Iframes
Using held-open connections there are two more ways to update a page, however these do not work reliably in all cases:
Animated GIF
CSS DIV tags with absolute positioning.
Note that this needs that your Server can keep open a session for each person looking at the page, which can be thousands. If this does not work the only possible workaround is with FRAMEs and automatic refresh, which is somewhat clumsy.
As I think that you do not want to use Frames and you do not want to render animated GIFs, I explain the CSS DIV way:
When you load the page you do not finish loading it. Instead the connection is kept open by the web server and the script handling the connection waits for additional information to arrive. When there is additional data, this is sent to the browser by encapsulating it into additional DIV tags which can overwrite other parts of the page.
Using "style" in the DIV tag and CSS position:absolute these can overwrite other information on the page like a new layer. However you need either position:absolute or must add this data to the end of the page.
How does this work with forms?
Forms usually have a known size so you can put them into IFRAMEs. These IFRAMEs get submitted to the webserver. The script there notifies the other script that new data must be output, so the waiting script renders the response and displays it in the page while the script which took the submit redisplays the form with fresh values only.
How does this work with 404 and anchors?
I don't really know because this must be tested, but here is a hint how I would try to implement this:
We have 2 issues here.
First the URL must not point to other pages but back to a server script again, so the href is under control. This script then notifies the waiting script to update the page accordingly, for example by retrieving the page and sending it to your browser. The script can check for 404 as well.
Second you must hinder the browser to switch the page when clicking on the anchor. This probably involves some clever tricks using CSS, target and server side status codes (like "gone" or redirect to the current page, whatever) to keep the browser from switching the page. I am not completely sure if that works, but if you remember download pages, these show URLs which do not switch the page but have an effect (downloading the file). That's where to start to try to hack browsers not leaving the current page without using JavaScript.
One idea not followed here is not keeping the connection of the page open but the CSS file and send new css information to the browser which then "fills in empty stubs" using the CSS way. But I doubt that this works very well, most browsers probably will parse the CSS only after loading finished, but perhaps I am wrong.
Also note that keeping a connection open never finishes the page loading, so you will see the busy-logo spinning all the time, which is unavoidable with this technique.
Having said this all I doubt you get around JavaScript.
What I wrote here is very difficult to do and therefor usually is not used because it scales badly. And it is a lot more difficult than using JavaScript alone (that's why I explained it).
With proper AJAX it is much more easy to reach your goal. Also note that you do not need to change your page source much, all you need is to add a script which augments the page content such, that for example forms suddenly use AJAX instead of a direct POST with re-rendering the page. Things which cannot be detected easily then need some hints in the tags such that the tag scanner knows how to handle the tag. The good thing then is, that with JavaScript switched off your page still works - however it then "leaves the page".
Normal HTML just was not designed to create application-like web pages like we want to see today. This all was added using JavaScript.
About popup forms
The Basic-Auth-Handler reloads the page after the user enters something into this dialog, only if cancel is hit the current page is displayed.
But there are two ways to present additional query-popups in a page using JavaScript:
The first one is the javascript "prompt", like in following example:
http://de.selfhtml.org/javascript/objekte/anzeige/window_prompt_vor.htm
(Click on the "Hier").
The second one is "JavaScript forms" which are like popups within an HTML-page.
However I consider popups to be far too intrusive and bad design.
Ajax and JavaScript is the easiest way
Unfortunately using JavaScript is never easy, but if you think JavaScript is improper or too difficult, there is no other technique which is easier, that's why JavaScript is used everywhere.
For example your page onload-Script can cycle through all Anchor-Tags and modify them such, that clicking on them invokes a function. This function then must do something clever.
Same is true for Forms. Fields which can be modified (like the user's eMail address) then have two views, on is visible, the other one hidden. The hidden one is a form. Clicking on the eMail address then switches the view (disables the first div and enables the second), such that suddenly instead of the eMail address a text form field is there containing the eMail address. If you click on the "OK" button the button changes the look into a spinner until the data is submitted, then the view switches back to the normal one.
That's the usual way to do it using JavaScript and Ajax. And this involves a lot of programming until it works well.
Sorry for not shortening this post and missing code snippets, I am currently lacking time ;)
Hidden iframe.
Set target attribute of the form to the name of the iframe. use the onload event of the iframe to determine what is the response.
Or, if you really dont like any javascript, don't hide the iframe and instead present it in a creative manner.
CSS to hide an element
#myiframe { position:absolute; left: -999em; display: none; visibility: hidden; }
But normally, display: none is enough. This is just an overkill.
I'm having hard time trying to figure out how to auto-save user data in a form when the browser is being closed or user changes the page. The onBeforeUnload event is OK when you want to open a dialog box, but by then it's too late to save the changes (except if you just block the browser in the onBeforeUnload handler long enough for it to pass the request to the server...but I'd rather not do that).
I am sure some of you have had to deal with the unsaved form problem. What do you do? Do you:
let users just lose their changes,
ask them using a modal window if they are sure they did the right thing,
save individual fields on the fly as they change,
or do you have some ultimate method to automagically save the data when it's about to be lost irretrievably?
•ask them using a modal window if they are sure they do the right thing,
Closing a window is an act of cancellation. As the user never actively submitted the form, theres no guarantee that they want the data saved (it may not be correct), and you saving the data could cause problems for the user.
I like your third option:
save individual fields on the fly as they change.
I'm having to deal with a similar situation, and that's what we are doing. The two main things that sell that to me:
Improved user experience - the user
will be impressed by a form that
does not lose changes. They are
'committed' once they are validated.
E.g., he types in a valid email
address, and it is saved instantly,
furthermore he is provided some sort
of feedback for each field that is
successfully been saved (a green
tick for example, appears next to
the field).
No more 'oh crap my browser crashed
and I lost all my info' situations.
Disadvantages: The extra man-hours involved in developing such a solution, and the possibly that it ends up not degrading as nicely as a simpler solution. That said, it is still worth it IMO.
In any browser I have used it in, onBeforeUnload provides you with a modal window which asks the user to confirm whether they want to leave the page or not. You can added your own text warning them that there is unsaved data, to help them decide. You don't want to explicitly save without the user's request, because a) the user did not attempt to save, and b) if you need to throw any validation errors it will be too late as the page is already in the process of navigating away.