How to prevent repeatative submit while using ajax or javascript? - javascript

I have a controller in c# and inside the controller there is a save method. The save method saves/updates data that is submitted by submit button click and javascript. The problem is, if you click on the button multiple time, it should only process the very first click and rest of them should be identified as duplicate submit and should be discarded by controller. How to do this in c# mvc web application?

Disable the button after it's clicked. So it can just be clicked once.

Simple way
when button clicked disabled it then actived again after you got response result from ajax! u can also add loader that make ur web look so cool!
<button id="btnSend" onClick="send()">submit</button>
<script>
btnSend=document.getElementById("btnSend");
function send(){
btnSend.disabled=true;
//set disabled button here
$.ajax({ type: "GET",
url: "http://www.google.de",
async: false,
success : function(text)
{
btnSend.disabled=false;
//set active to button
// add your code here
},
fail : function(text)
{
btnSend.disabled=false;
//set active to button
// add your code here
}
});
}
</script>

I would also disable the button on the client side. But you could also check if the submitted data is different from the stored data. If no changes were made you could just return without further saving logic.
Should it be possible to just save the data once? Maybe a redirect to a different view after saving could be a possible solution in special cases.

Related

When I disable submit button (after form submit) the page does not load

I have an HTML form which submits to another page via POST. Nothing special about it, except that after the form validates I try to hide and/or disable the submit button so that it cannot be double-submit, while also telling the user the next page might take a while to load.
The relevant code is:
jQuery(document).ready(function () {
jQuery("form#form").submit(function() {
var result = validate();
jQuery(this).find('input[type=submit]').prop('disabled', true);
jQuery("#submit-button-wrapper").html(jQuery("#submit-button-wrapper").html()+
"<br/><br/><span style='margin: 25px; padding: 5px; background: yellow; "+
"width: 100%; font-weight: bold;'>Loading... this may take a few minutes! "+
"<i class='fa fa-spinner fa-spin' style='color: blue;'></i></span>");
return result;
});
});
function validate() {
return true; // Does stuff, then returns a simple true or false
}
By request, here is the (very simple) button wrapper HTML:
<div class="col-sm-12" id="submit-button-wrapper">
<input type="submit" value="One More Step" />
</div>
When the I remove the which changes the button wrapper's HTML, the form submits just as you'd expect. When I have that line in, however, it still calls the next page and executes that code, without the displayed page ever changing.
I have tested in both Chrome and Firefox, so I know it's not a browser issue, but this is really weird behavior. What am I doing wrong?
My goal: (1) validate the user's input, (2) give the user a clue that the page is going to take a while to load and (3) display the output from the action="complete.php" page once the PHP on it has run.
Maybe you can achieve this with $ajax and show results on the same page.
Send POST data to /some.php
After sending data, give feedback to user changing button behavior
When the task is complete, receive data and verify success or error and act accordingly. If OK, change button text to "complete!" or something else, and append response data to some div. If NOT OK, give feedback as well.
In code:
$("form#form").submit(function(e) {
e.preventDefault();
$.ajax({
method: "POST",
url: "some.php",
data: $(this).serialize(),
dataType : 'json',
timeout: 2000,
cache: false,
afterSend: function() {
/*change button behavior here*/
},
success: function(result) {
if (result === "ok"){
/*maybe append data to div and update button text to complete*/
} else {
/*if result not ok, send feedback*/
}
}
});
});
BTW: ajax documentation http://api.jquery.com/jquery.ajax/
When you return true (if validated) then the form is submitted. However, you're changing the DOM / submit button wrapper and essentially removing the submit button, right? Likely that is what is causing your problem. Leave the submit button wrapper alone. If you want to display a message display it as an overlay or hide the submit button wrapper and show the message wrapper in its place, don't remove the submit button altogether.
I know that you're just showing a slight jQuery and HTML portion of the script, but that isn't quite enough to figure out your problem. Since not all of it seems to be there because you mention action="complete.php" but I don't see that within your jQuery or HTML sample of code. So I have a few questions of my own.
Is the form small or large. If it's a small form then why aren't you displaying the output on the submit page? You could do that with what you currently have but a single PHP or ASP page could save you on amount of pages to make and what not. As a side note, depending on size of the form, you can do the validation on same page or continue to use action="" for it if large.
Do you have need for a database file or are you saving to one? If you do/are, you could write to the DB file, have the submit open the next page and view what was saved in the database on that new page. Again, you can probably use a single PHP or ASP page.
This last part sounds more valid for your purpose. You could use location.href="http://www.domain.com/home.html";
or use window.location("http://www.domain.com/home.html"); to redirect to the new page.
On another matter about some of the comments others made.
You don't exactly need the + unless you're dividing each of those out into their own separate lines when you could just use one line to do that. That's probably what confused Rajesh about the '. In fact I'm not sure why you yourself mentioned the + when referring to Rajesh comment about "concat string" and "append" ,because those two have nothing to do with the +. In fact to take a guess, he might have been referring to your jQuery("#submit-button-wrapper").html(jQuery("#submit-button-wrapper").html() which kinda looks like a concat string.
Speaking about append, not really needed unless for example you're doing something like giving the user the option to add rows to a form question.

How to stay on same position after submitting an html form?

I have a simple html form:
<form action="addToCart" method="post"><br><br>
<input name="productId"
value="${product.id}" type="hidden"> <input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>"
type="submit">
</form>
Every time I click on "submit", it brings me straight back to top which creates a poor user experience because the user would have to scroll back down where he was browsing the products... Can I do this without using a script?
-Every time I click on "submit", it brings me straight back to top.
Yes that is what default functionality when submitting forms, it always repaints the dom so it causes a jump and page's top position is rendered.
-which creates a poor user experience because the user would have to scroll back down where he was browsing the products
To make a good user experience you can use ajax for this functionality, as you tagged jQuery in your question then you can try with jquery ajax:
$('form').submit(function(e){
e.preventDefault(); // stops the form submission
$.ajax({
url:$(this).attr('action'), // action attribute of form to send the values
type:$(this).attr('method'), // method used in the form
data:$(this).serialize(), // data to be sent to php
dataType:"text",
success:function(data){
alert(data); // you can alert the success message.
},
error:function(err){
console.log(err);
}
});
});
I have used a dataType:"text", just assuming if you are going to echo "Added in the cart."; kind of message from the php.
Ajax is your best bet if you want to achieve what you want
$('.submit').on('click',function(event){
event.preventDefault(); //this is important else page will get submitted
$.ajax({
url:'where you want to process data',
dataType:'html',
data: your form data as json or whatever type
success: function(result){
//here you can update any thing on the frontside
}
});
});
Since you're using onclick attribute on your button, you have to change type attribute from submit to button. That way you can get your addedCart() method to fire. Then handle form submission inside that method (if your submit handler isn't already there).
<input class="submit" onclick="addedCart()" value="<fmt:message key='AddToCart'/>" type="button">
Script:
function addedCart(){
// ... your method on click
// $.ajax({...});
};
If you're not using jQuery, you can handle form submission with XMLHttpRequest :
How to make an AJAX call without jQuery?

How do you use twitter bootstrap button with jquery?

What I want to do is when a user clicks on the submit button in a forum, it should send the data collected to the php script and ideally, stay on the same page. Currently, I have in the form(I have other tags in the form but these are the two things I need to focus on)
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
As you can see, I use a form that sends the data to sqlinserter.php when the user clicks the submit button. Basic form stuff. Right now, when it clicks submit it goes to the actual sqlinsert.php page which is blank because it is just sending data to the database.
However, I would like to create a simple jquery script where you click the button it sends the data using ajax. I have been noticing that twitter bootstrap works differently with buttons and I am not sure how to use their buttons with jquery. Any help with this would be great.
So,
I need to figure out how to use twitter bootstrap buttons with
jquery. Specifically, I need to figure out how to use the submit
button.
How to send data using ajax?
I need to figure out how to use twitter bootstrap buttons with jquery. Specifically, I need to figure out how to use the submit button.
Bootstrap can be used together with jQuery, no additional steps required. Actually even bootstrap itself use jQuery in their framework.
You can still use jQuery like usual, and bootstrap like usual. Both will work, without any conflicts.
How to send data using ajax?
It can be done by using one of jQuery AJAX function, for example $.ajax.
Just add new event, click, on your button #newThread. Write the AJAX inside the event handler. Example based on your code can be seen in below.
HTML
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
</form>
JS
$(function() {
$('#newThread').on('click', function (e) {
e.preventDefault(); // disable the default form submit event
var $form = $('#replyForm');
$.ajax({
url: $form.attr("action"),
type: $form.attr("method"),
data: $form.serialize(),
success: function (response) {
alert('response received');
// ajax success callback
},
error: function (response) {
alert('ajax failed');
// ajax error callback
},
});
});
});
There isn't any specific way to use a twitter bootstrap button. Just grab the id of this submit and submit the data via ajax like below:
$.ajax({
type:'GET',
dataType:'xml',
url:'path/to/phpfile.php',
success:function(data) {
// Do the handling here
},
error:function() {
alert("Sorry, Ajax call Failed");
}
});
There is nothing specific to form submission with bootstrap. You just need to make sure the button is insde the form (which you should want even if it wasn't bootstrap).
<form name = "reply" id="replyForm" action="sqlinserter.php" method = "POST">
<button id = "newThread" class="btn btn-primary" type="submit">Submit</button>
</form>
you are missing the closing </form> tag

unable to give exact target to refresh my div in jquery function

sir,
when i click on "Rename Day button" jquery popop calender appears in my screen , once if i click on its submit button it is forwarding to my page but is not refreshing the exact div.. I do not where should i specify div target for refreshing my particular div..
jquery function for submit
function okButton(){
$("#formId").submit();
};
$(this).submit({
target: '#userTemplateRightmiddlediv'});
};
struts.xml
<!-- Rename Selected Day for User Template -->
<action name="EditDayAction"class="com.ebhasin.fitnessbliss.dao.DynamicTableOperationsService" method="RenameDayUserTemp">
<result name="success">/jsps/userTemplateRightmiddlediv.jsp</result>
</action>
Extend the functionality of your 'okButton' to stop the default form submission behavior, then create an ajax function to connect to your XML file, return the data, and then insert the data into the .html() of the element with an ID of userTemplateRightmiddlediv
function okButton(){
$("#formId").submit(function(e){ //'e' for 'event'
e.preventDefault();//stop the page from refreshing
$.ajax({
url: 'Struts2 URL Here',
dataType: 'xml',
success: function(xml){
//function(xml) represents an object returned from our XML file, we can work with it however we want by using normalized jquery procedures
$("#userTemplateRightmiddlediv").html(xml);
}
});
});
}
Edit
Changed to reflect portability with Struts 2.
You're trying to fire two submits. $ is a function that returns an object. 'submit' is a method of that object. If the jquery object is holding a form, it's like pressing the submit button on that form so the page refreshes and all the remaining code doesn't matter. You're trying to submit twice but $(this).submit doesn't really make sense.
If I had to guess, maybe you want something more like this:
$('#formId').submit( function(e){
e.preventDefault(); // stops the page from reloading
//maybe ajax or something else to change this div you're talking about.
} )

AJAX jquery Form Post not working

I am trying to post a form using ajax.
Right now, the code I have is
$("#sub").click(function() {
var tag = $("#tagbar").val();
var opinion = $("#op").val();
alert($("#expressform").serialize());
$.post("dbfunctions.php", $("#expressform").serialize());
});
This works, but it takes a long time to post and add to the database (thats what dbfunctions does) compared to how long it took before, when I was using a form action and refreshing the page. Why is this?
Also, if I remove the alert, the script stops working completely. I can't figure out anyway in which this makes sense.
Thanks
Make sure you cancel the default action of the button by returning false from the click handler:
$("#sub").click(function() {
$.post("dbfunctions.php", $("#expressform").serialize());
return false;
});
Also instead of subscribing for submit button clicks, it's better to subscribe to the submit event of the corresponding form directly:
$("#expressform").submit(function() {
$.post(this.action, $(this).serialize());
return false;
});
This way you are no longer hardcoding any urls in your javascript files. You are simply unobtrusively AJAXifying your form.
You can use below function for submit the data
through Ajax form Submit
$('#form1').ajaxForm({
success:function(response){
$('#save_data').html(response);
});
$('#btnSubmit').click(function() {
$('#form1').submit();
});

Categories

Resources