Rails: Prevent duplicate entry from simultaneous submission - ruby-on-rails

We're having a problem with our app allowing people to sign up multiple times with the same account information (email, specifically).
Our user model validates the uniqueness of the email parameter, and we are also using some javascript to make sure that once the "sign up" button is clicked, it becomes unusable unless the sign up fails (theoretically ensuring only a single click).
It appears that the problem stems from users double-clicking the signup button before the javascript on the page finishes loading.
Is there a way from the Rails side that we can prevent this? Maybe something that creates a request stack, and then iterates through them? I ask because we can't be the only site that has this issue.
Thanks

Dumb question: Why don't you set the field in the database itself to unique?
If that is not possible, do what Steve Bourne suggested and use something like this:
var clicked = false;
$('#submit_button').click( function() {
$(this).preventDefault();
if(!clicked) {
clicked = true;
$('#submit_button').attr('disabled','disabled');
$('#form').submit();
}
Now, I didn't test that so setting clicked = true may be overkill ;)

Set the text field to Nothing right after the insert.

Not entirely convinced that's what's happening, but another option would be to only enable the submit button in jQuery's ready function, and start off with it hidden or disabled. Are you running a large amount of JS outside of the ready function?

If the problem is that users submit the form before your javascript is finished loading, why not make that impossible? (i.e. the submit button action doesn't submit the form, but your javascript submits on the click event?)
There are a few ways to then prevent dupes in JS; sounds like you've got that covered already.

Related

How can we circumvent these remote forms drawback?

In an effort to have everything translateable in our website ( including the error messages for the validations ), we switched almost all of our forms to remote forms. While this helps with the ability to translate error messages, we have encountered other problems, like:
if the user clicks on the submit button multiple times, the action gets called multiple times. If we have a remote form for creating a new record in the database, and assuming that the user's data is valid, each click will add a new object ( with the exact same contents ). Is there any way of making sure that such things cannot happen?
Is there somewhere I could read about remote forms best practices? How could I handle the multiple clicks problem? Is switching all the forms to remote forms a very big mistake?
There is a rails 3 option called :disable_with. Put this on input elements to disable and re-label them while a remote form is being submitted. It adds a data-disable-with tag to those inputs and rails.js can select and bind this functionality.
submit_tag "Complete sale", :disable_with => "Please wait..."
More info can be found here
Easy, and you can achieve that in many ways depending your preferences:
Post the form manually simply using an ajax request and while you wait for the response disable/hide (or whatever you need) the form to ensure the user can't keep doing posts as crazy. Once you get the response from the server, again you can allow the user to post again (cleaning the form first), or show something else or redirect it to another page or again whatever you need.
Use link_to :remote=>true to submit the form and add a callback function to handle the response and also to disable/hide (or whatever you need) the form when it's submitted
Add a js listener to the form to detect when it's submitted and then disable/hide/whatever the form
As you see, there are lots of different ways to achieve what you need.
EDIT: If you need info about binding or handling a form submit from js here you'll find very easy and interesting examples that may help you to do what I suggested you! jQuery Submit
I have remote forms extensively myself, and in most cases I would avoid them. But sometimes your layout or UX demands for on-the-fly drop-down forms, without reloading or refreshing the complete page.
So, let me tackle this in steps.
1. Preventing Normal form double-post
Even with a normal form, a user could double-click your button, or click multiple times, if the user does not get a clear indication that the click has been registered and the action has started.
There are a lot of ways (e.g. javascript) to make this visible, but the easiest in rails is this:
= f.button :submit, :disable_with => "Please wait..."
This will disable the button after the first click, clearly indicating the click has been registered and the action has started.
2. Handling the remote form
For a remote form it is not that much different, but the difference most likely is: what happens afterward ?
With a remote form you have a few options:
In case of error: you update the form with the errors.
you leave the form open, allowing users to keep on entering the data (I think this is your case?)
you redirect the users to some place.
Let me handle those cases. Please understand that those three cases are completely standard when doing a normal form. But not when doing a remote call.
2.1 In case of error
For a remote form to update correctly, you have to do a bit more magic. Not a lot, but a bit.
When using haml, you would have a view called edit.js.haml which would look something like
:plain
$('#your-form-id').replaceWith('#{j render(:partial => '_form') }');
What this does: replace the complete haml with only the form. You will have to structure your views accordingly, to make this work. That is not hard, but just necessary.
2.2 Clearing the form
You have two options:
* re-render the form completely, as with the errors. Only make sure you render the form from a new element, not the just posted one!!
* just send the following javascript instead:
$('#your-form-id').reset();
This will blank the form, and normally, that would effectively render any following clicking useless (some client validation could block posting until some fields are filled in).
2.3 Redirecting
Since you are using a remote form, you can't just redirect. This has to happen client-side, so that is a tad more complicated.
Using haml again this would be something like
:plain
document.location.href = '#{#redirect_uri}';
Conclusion
To prevent double (triple, quadruple, more) posts using remote forms you will have to
disable the button after first click (use :disable_with)
clear the form after succesful submission (reset the form or render with a new element)
Hope this helps.
The simplest solution would be to generate a token for each form. Then your create action could make sure it hasn't been used yet and determine whether the record should be created.
Here's how I would go about writing this feature. Note that I haven't actually tested this, but the concept should work.
1.
Inside the new action create a hash to identify the form request.
def new
#product = Product.new
#form_token = session["form_token"] = SecureRandom.hex(15)
end
2.
Add a hidden field to the form that stores the form token. This will be captured in the create action to make sure the form hasn't been submitted before.
<%= hidden_field_tag :form_token, #form_token %>
3.
In the create action you can make sure the form token matches between the session and params variables. This will give you a chance to see if this is the first or second submission.
def create
# delete the form token if it matches
if session[:form_token] == params[:form_token]
session[:form_token] = nil
else
# if it doesn't match then check if a record was created recently
product = Product.where('created_at > ?', 3.minutes.ago).where(title: params[:product][:title]).last
# if the product exists then show it
# or just return because it is a remote form
redirect_to product and return if product.present?
end
# normal create action here ...
end
Update: What I have described above has a name, it is called a Synchronizer (or Déjà vu) Token. As described in this article, is a proper method to prevent a double submit.
This strategy addresses the problem of duplicate form submissions. A synchronizer token is set in a user's session and included with each form returned to the client. When that form is submitted, the synchronizer token in the form is compared to the synchronizer token in the session. The tokens should match the first time the form is submitted. If the tokens do not match, then the form submission may be disallowed and an error returned to the user. Token mismatch may occur when the user submits a form, then clicks the Back button in the browser and attempts to resubmit the same form.
On the other hand, if the two token values match, then we are confident that the flow of control is exactly as expected. At this point, the token value in the session is modified to a new value and the form submission is accepted.
I hate to say it, but it sounds like you've come up with a cure that's worse than the disease.
Why not use i18n for translations? That certainly would be the 'Rails way'...
If you must continue down this route, you are going to have to start using Javascript. Remote forms are usually for small 'AJAXy things' like votes or comments. Creating whole objects without leaving the page is useful for when people might want to create lots of them in a row (the exact problem you're trying to solve).
As soon as you start using AJAX, you have to deal with the fact that you'll have to get into doing some JS. It's client-side stuff and therefore not Rail's speciality.
If you feel that you've gone so far down this road that you can't turn back, I would suggest that the AJAX response should at least reset the form. This would then stop people creating the same thing more than once by mistake.
From a UI/UX point of view, it should also bring up a flash message letting users know that they successfully created the object.
So in summary - if you can afford the time, git reset and start using i18n, if you can't, make the ajax callback reset the form and set a flash message.
Edit: it just occurred to me that you could even get the AJAX to redirect the page for you (but you'd have to handle the flash messages yourself). However, using a remote form that then redirects via javascript is FUGLY...
I've had similar issues with using a popup on mouseover, and not wanting to queue several requests. To get more control, you might find it easier to use javascript/coffeescript directly instead of UJS (as I did).
The way I resolved it was assigning the Ajax call to a variable and checking if the variable was assigned. In my situation, I'd abort the ajax call, but you would probably want to return from the function and set the variable to null once the ajax call is completed successfully.
This coffeescript example is from my popup which uses a "GET", but in theory it should be the same for a "POST" or "PUT".
e.g.
jQuery ->
ajaxCall = null
$("#popupContent").html " "
$("#popup").live "mouseover", ->
if ajaxCall
return
ajaxCall = $.ajax(
type: "GET"
url: "/whatever_url"
beforeSend: ->
$("#popupContent").prepend "<p class=\"loading-text\">Loading..please wait...</p>"
success: (data) ->
$("#popupContent").empty().append(data)
complete: ->
$"(.loading-text").remove()
ajaxCall = null
)
I've left out my mouseout, and timer handling for brevity.
You can try something like that for ajax requests.
Set block variable true for ajax requests
before_filter :xhr_blocker
def xhr_blocker
if request.xhr?
if session[:xhr_blocker]
respond_to do |format|
format.json, status: :unprocessable_entity
end
else
session[:xhr_blocker] = true
end
end
end
Clear xhr_blocker variable with an after filter method
after_filter :clear_xhr_blocker
def clear_xhr_blocker
session[:xhr_blocker] = nil
end
I would bind to ajax:complete, (or ajax:success and ajax:error) to redirect or update the DOM to remove/change the form as necessary when the request is complete.

How can I manipulate a form / inputs to be ignored when a form is submitted

I'm using ExpressionEngine and SafeCracker along with Ajax (plugin: jquery.form.js - http://jquery.malsup.com/form/).
Best I can tell, SafeCracker will only allow for updating a single entry at a time. However, the UI / UX necessitates that a list be displayed. I've proof of concept'ed an entry by entry on-demand form. That is, click a particular edit link next to each entry and a snippet of jquery creates a form along with displaying a submit button. Click submit and that single entry updates. The inputs don't exist until the Update link is clicked
What I would prefer to do, if possible, is to create the non-form and form versions of each entry as the page is renbered and use some sort of toggle to display one or the other. Again, doable. Then, when I click the Edit link I'd add the necessary attributes to the input so that entry's form elements will be read but the other (display: none) elements for the other entries will be ignored. I'm thinking (out loud) that if I add the attr("name", some-value) that would work. That is, an input with no name will be ignored.
Yes, I can test this and I will. However, even if it works I'm not sure if it's a best practice and/or there's a more ideal way of accomplishing my ends. I'm here looking for validation and/or additional expertise and input.
Thanks in advance.
Just set disabled property to inputs and they will excluded from Form submission, whatever input fields are hidden or visible. Different jQuery methods, like submit() and serialize() follow specification of HTML 4 and exclude all disabled controls of a forms. So one way is to set
$('your_input').prop('disabled', true);
or ,
$('your_input').attr('disabled', 'disabled');
Check following link:
http://www.w3.org/TR/html401/interact/forms.html#successful-controls
Also, you may use a general button instead of a submit, as result you can handle click event on it and within that event you can make exclusion, validation, manipulation on values and what ever you like.
You can put a disabled attribute on them server side or set the property via jQuery:
$(".hidden input").prop("disabled", true);

Asp.Net Mvc remote validation textbox focus issue

I have a single textbox on a form - basically to allow users to change the URL of their site in our mini CMS. We use remote validation to check that the URL is not already taken.
They enter their desired URL and hit the save button. If they do just that and the focus goes from the textbox straight to the submit button - the validation does not happen and the form doesn't submit properly. If they tap into an area of whitespace then the form does.
The issue with the form submitting is that if they tap whitespace we get the name of the submit button posted along with the desired URL - we use the (AcceptParameterAttribute) to allow us to route form submits to the right Action. This uses the submit buttons name attribute to do this. If they don't click whitespace to lose focus on the text box then only the desired URL is posted.
This is a really odd one and it is very annoying. Has anyone seen anything like this before? Is there a way to overcome the problem?
Try adding the following script to the page:
$(":input").live("blur", function () {
$(this.form).validate().element(this);
});
This should cause validation to occur when you click on the submit button. If not, try changing the first line to:
$(":submit").live("click", function () {

Update attribute on check box click (Rails 3)

I've been searching forever to find an actual answer to this:
What would be the best way to update an object's attribute via ajax when a checkbox is clicked? It's simply a matter of wanting to flip an attribute from false to true and vice versa.
There are one or two threads on stackoverflow about this, but they either employ observe_field (I'd rather just do it with a Prototype function) or have never solved the problem at all, it seems.
Again, this is Rails 3 and Prototype.
I guess it's the checkbox part that's tripping you up?
All you really need to do is have a method in your model to toggle the appropriate field
# somewhere in your model
my_boolean_field.toggle
and then bind a .click() handler to your checkbox to do an ajax request. If you need to, in the .click() handlers callback you can update the checkbox but I'm not sure if that's necessary.
The only part that's tricky here is what to do if the user clicks the checkbox quickly several times. One option is to disable the checkbox after it's clicked until the callback finishes.

Is there a way to change the browser's address bar without refreshing the page?

I'm developing a web app. In it I have a section called categories that every time a user clicks one of the categories an update panel loads the appropriate content.
After the user clicked the category I want to change the browser's address bar url from
www.mysite.com/products
to something like
www.mysite.com/products/{selectedCat}
without refreshing the page.
Is there some kind of JavaScript API I can use to achieve this?
With HTML5 you can modify the url without reloading:
If you want to make a new post in the browser's history (i.e. back button will work)
window.history.pushState('Object', 'Title', '/new-url');
If you just want to change the url without being able to go back
window.history.replaceState('Object', 'Title', '/another-new-url');
The object can be used for ajax navigation:
window.history.pushState({ id: 35 }, 'Viewing item #35', '/item/35');
window.onpopstate = function (e) {
var id = e.state.id;
load_item(id);
};
Read more here: http://www.w3.org/TR/html5-author/history.html
A fallback sollution: https://github.com/browserstate/history.js
To add to what the guys have already said edit the window.location.hash property to match the URL you want in your onclick function.
window.location.hash = 'category-name'; // address bar would become http://example.com/#category-name
I believe directly manipulating the address bar to a completely different url without moving to that url isn't allowed for security reasons, if you are happy with it being
www.mysite.com/products/#{selectedCat}
i.e. an anchor style link within the same page then look into the various history/"back button" scripts that are now present in most javascript libraries.
The mention of update panel leads me to guess you are using asp.net, in that case the asp.net ajax history control is a good place to start
I don't think this is possible (at least changing to a totally different address), as it would be an unintuitive misuse of the address bar, and could promote phishing attacks.
This cannot be done the way you're saying it. The method suggested by somej.net is the closest you can get. It's actually very common practice in the AJAX age. Even Gmail uses this.
"window.location.hash"
as suggested by sanchothefat should be the one and only way of doing it. Because all the places that I have seen this feature, it's all the time after the # in URL.

Resources