Disable Button Call Server then Re-enable Button - javascript

I've seen many similar questions to mine, but have spent a few hours browsing and can't find the answer to my situation.
I have a Go based web-server. I have an HTML template page that lets me update the hardware clock and system clock on a 'nix system with the current browser time:
The update button is of type submit and calls the Go code which makes some system calls which take a few seconds, and I can't have this server code being called twice whilst it's still processing the first request.
So I want to disable the update button and then re-enable it once the server has responded.
I have jQuery, so I know I can have a function that is called via `onclick' and make these calls:
$("#updateButton").prop("disabled", true);
$("#updateButton").prop("disabled", false);
I have the form being submitted via the button (and not a jQuery call for instance - although I'm all ears) because I want the form to refresh when the server responds. So I have this:
<form action="/clock" method="POST">
...
</form>
This is so some values on the page get updated. Such as the status message at the top and the values in the various fields (updated to the values actually set).
The first problem I have is that if I call a JS function on the button click, and it disables the button as per above, then my server code doesn't get called! I have no idea why - could this be stopping the post request somehow?
<script>
function getTime() {
// Disable update button while waiting for response
$("#updateButton").prop("disabled", true); // Stops post request???
// How to re-enable update button?
}
</script>
And secondly, how do I re-enable the button? I don't know how to tell when the server has responded.

Since you're saying you want to disable the submit button once the button is clicked. And you're also saying you want the page to refresh while the form is being submitted.
<form action="" method="post" onsubmit="subBtn.disabled = true; return true;">
<input type="submit" name="subBtn" value="submit"/>
</form>
In the code above, when <form> is submitted, <input> field named subBtn is disabled and true is returned for <form> to continue the submission process. Once the page is reloaded, the button goes to its original state, which is enabled.
I am not sure whats going on the code down there or how/when is getTime() function executed, but return true; might just submit the form.
<script>
function getTime() {
$("#updateButton").prop("disabled", true);
return true; // this to continue with the original <form> process
}
</script>

Related

How to disable button when clicked button to action window location and enable it again after window location finished [duplicate]

When I am clicking a submit button on my HTML form, the function related to the button is called and it does its work. After completing the work a mail notification is sent which is consuming too much time. After that a confirmation message is displayed on the same HTML page (without using Ajax; i.e., the page is refreshed).
I want to avoid letting the user click the submit button multiple times in confusion during the waiting period of sending mails. So I am thinking that I should disable the button after it is pressed once.
How can I do this?
Can you please suggest any other technique to achive this goal without disabling the button?
Simply:
<form action="file" method="post" onsubmit="this.submit_button.disabled = true;">
<input name="submit_button" type="submit" value="Submit" />
</form>
You can achieve this without disabling the button by using a nonce, however it is a bit more complex. Essentially, when the user requests the page that has the form that will be submitted, assign a unique id to that user's request (store it somewhere on the server, and make sure it's submitted along with the form). When the form is then submitted, look up the unique id to make sure it's not in process or already processed, and then if it's OK to proceed, mark the unique id as "in process", process the form, and then mark it as processed. If when you do the initial check and the page is in process or already processed, you'll need to take the necessary action (redirect them to a confirmation page if it was successfully processed, or back to the form if it was not successfully processed).
How can I do this?
You can take a look at the javascript code in this page:
http://www.codinghorror.com/blog/archives/000096.html
<input type="Button" onClick="this.value='Submitting..';this.disabled=true;" value="Submit">
Can you please suggest any other technique to achive this goal without disabling the button?
Show a busy panel:
"... Your request is being processed please wait..."
(source: vodafone.co.uk)
If you disable a button right before submitting, then the parent form will not be submitted. You need to disable the button after submitting. Best way it to use JavaScript's setTimeout() function for this.
<input type="submit" id="foo" onclick="setTimeout('document.getElementById(\'' + this.id + '\').disabled=true;', 50);">
50ms is affordable enough to give the form the chance to get submitted.
To enhance the user experience more, you could of course append a message or a loading image dynamically during the same onclick event as already suggested by others.
Assuming you don't want to disable the button you could always pop up a modal on the page. This will block the user's interaction with the page. You could throw some kind of loading spinner in there with a message that the submit is in progress.
I don't understand why it is a problem, as you are doing a regular submit, the user should see a white page while you are processing in the back end.. But in case if you want to disable the button, here is the code, use it on the button
onclick="this.disabled=disabled"
You could have the button be disabled, but still seem active to the user. In the function that gets called after the button is hit the first time, have the first thing it does set a global variable like disableButton to true. When the user presses the button, have that go to a function called something like checkSubmitStatus. If disableButton = true, return false. if disableButton = false, trigger the submit function.
You have still disabled the button, but your users can press away unaware.
I'm not submitting anything, but Google Chrome 31 doesn't update the button look while calculating, so i came up with this workaround:
<style>
.btnMenu{width:70px; font-size:12px}
.btnMenu:disabled{background-color:grey}
</style>
<input type="button" class="btnMenu" value="Total" onmousedown="b=this; b.disabled=true; b.v=b.value; b.value='Calculating...'; setTimeout('updateTotals(); b.value=b.v; b.disabled=false', 100)"/>

XHR call using plain JavaScript

I am having issue with XHR call made to GitHub domain from localhost.
Upon clicking on the button Click to get User Profile with Ajax+JS, a JS function getUser() gets called. Code works as expected, i.e., gets a particular GitHub user details(full name and avatar) and displays on the page.
## Code for "Click to get User Profile with Ajax+JS" button
<input type="button" value="Click to get User Profile with Ajax+JS" onclick="getUser()" id="jsBtn" />
BUT, when I call the same JS function on form submission using submit button (or return), it does not return the expected result i.e., user details.
## Code for "Submit" button
<form id="myForm" onsubmit="getUser()">
#...
<input type="submit"/>
</form>
Upon inspecting under Network, I see the difference in the way Request URL is formed in Request Headers Section:
## With GitHub username input as kirtithorat
## First Case With "Click to get User Profile with Ajax+JS" button
Request URL:https://api.github.com/users/kirtithorat
## Second Case With "submit" button
Request URL:http://localhost:3000/html_file_name?username=kirtithorat
Why the difference in behavior? The same JS function works for onclick but not for onsubmit.
NOTE:
I am looking for a Pure JS Solution. I know how to do it in
jQuery.
I don't actually want the form to be submitted, only the
onSubmit event should be triggered.
Here is my JSFiddle
Your second URL looks like the form submission, NOT the result of calling getUser() (the getUser() ajax call probably came right before the form submission).
If you don't want the form to actually submit (which it appears is how you want it) and only want your onSubmit handler to be called, then you need to make sure the default behavior of submitting the form is prevented.
You can block form submission by just adding a
return false;
to the end of your getUser() onsubmit handler function.
Or, you can block the form submission by passing the event into the getUser() function and using e.preventDefault().
The other reason to block the form submission is that the page will reload with the results of the form submission and your javascript will not still be active to receive the results of the getUser() ajax call. So, you must use one and only one of the Ajax call or the form submission (it looks like you just want the ajax call so you can prevent the form submission).

Use JavaScript to automatically submit form

I'm have a simple form, when clicking the submit button the backend php file gets executed by my JavaScript file, results are returned via ajax, everything works great when manually clicking the button. However, when trying to use javascript to automatically submit the form every 120 seconds it is not working. The javascript never get's called which in turn causes the php to not execute...
html
<form id="send-with-ajax" name="ping">
<input type="submit" value="Execute Ping" />
<div class="ajax-response"></div>
</form>
<script type="text/javascript">
// refresh ping results every 120 seconds
var pingRefreshInterval = setInterval(function () {
console.log(
'submitting ping.php request after 120 second wait - time now:'+new Date());
document.getElementById("send-with-ajax").submit();
},120000);
</script>
<script src="js/portal.js"></script>
Again, there are not issues with my portal.js file or my php file -- The main thing to note here is that the document.getElementById("send-with-ajax").submit(); does not do anything... Any ideas?
Assuming that js\portal.js just executes a function when a POST event occurs, you could simply call that function from inside your interval.
If that won't work for some reason (maybe there's a lot of other stuff happening on your page that you didn't show us), and your call to submit() isn't working properly, you could also trigger a button click with $('input[type=submit]').click(); (assuming you only have one submit button on the page - otherwise add a class or an id and trigger on that instead).
Try using the submit() method. Or use AJAX.
If you are doing things on onsubmit event, document.getElementById("send-with-ajax").submit() doesn't trigger this event.

Submit two forms with one button

I have HTML two forms, one that submits data upon entry to a database using PHP, the other directs the user to a paypal payment page, my problem is that the user would have to submit both forms which of course I do not want them to have to do. Is there anyway to use one submit button for two forms?
(Javascript is welcome)
You should be able to do this with JavaScript:
<input type="button" value="Click Me!" onclick="submitForms()" />
If your forms have IDs:
submitForms = function(){
document.getElementById("form1").submit();
document.getElementById("form2").submit();
}
If your forms don't have IDs but have names:
submitForms = function(){
document.forms["form1"].submit();
document.forms["form2"].submit();
}
A form submission causes the page to navigate away to the action of the form. So, you cannot submit both forms in the traditional way. If you try to do so with JavaScript by calling form.submit() on each form in succession, each request will be aborted except for the last submission. So, you need to submit the first form asynchronously via JavaScript:
var f = document.forms.updateDB;
var postData = [];
for (var i = 0; i < f.elements.length; i++) {
postData.push(f.elements[i].name + "=" + f.elements[i].value);
}
var xhr = new XMLHttpRequest();
xhr.open("POST", "mypage.php", true);
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send(postData.join("&"));
document.forms.payPal.submit();
You can submit the first form using AJAX, otherwise the submission of one will prevent the other from being submitted.
In Chrome and IE9 (and I'm guessing all other browsers too) only the latter will generate a socket connect, the first one will be discarded. (The browser detects this as both requests are sent within one JavaScript "timeslice" in your code above, and discards all but the last request.)
If you instead have some event callback do the second submission (but before the reply is received), the socket of the first request will be cancelled. This is definitely nothing to recommend as the server in that case may well have handled your first request, but you will never know for sure.
I recommend you use/generate a single request which you can transact server-side.
The currently chosen best answer is too fuzzy to be reliable.
This feels to me like a fairly safe way to do it:
(Javascript: using jQuery to write it simpler)
$('#form1').submit(doubleSubmit);
function doubleSubmit(e1) {
e1.preventDefault();
e1.stopPropagation();
var post_form1 = $.post($(this).action, $(this).serialize());
post_form1.done(function(result) {
// would be nice to show some feedback about the first result here
$('#form2').submit();
});
};
Post the first form without changing page, wait for the process to complete. Then post the second form.
The second post will change the page, but you might want to have some similar code also for the second form, getting a second deferred object (post_form2?).
I didn't test the code, though.
If you have a regular submit button, you could add an onclick event to it that does the follow:
document.getElementById('otherForm').submit();
if you want to submit two forms with one button you need to do this:
1- use setTimeout()
2- allow show pop up
<script>
function myFunction() {
setTimeout(function(){ document.getElementById("form1").submit();}, 3000);
setTimeout(function(){ document.getElementById("form2").submit();}, 6000);
}
</script>
<form target="_blank" id="form1">
<input type="text">
<input type="submit">
</form>
<form target="_blank" id="form2">
<input type="text">
<input type="submit">
</form>
javascript doesn't submit two forms at the same time. we submit two forms with one button not at the same time but after secounds.
edit: when we use this code, browser doesn't allow pop up.
if you use this code for your software like me just set browser for show pop up but if you use it in designing site, browser is a barrier and code doesn't run.

Disabling an HTML button while waiting for a result

When I am clicking a submit button on my HTML form, the function related to the button is called and it does its work. After completing the work a mail notification is sent which is consuming too much time. After that a confirmation message is displayed on the same HTML page (without using Ajax; i.e., the page is refreshed).
I want to avoid letting the user click the submit button multiple times in confusion during the waiting period of sending mails. So I am thinking that I should disable the button after it is pressed once.
How can I do this?
Can you please suggest any other technique to achive this goal without disabling the button?
Simply:
<form action="file" method="post" onsubmit="this.submit_button.disabled = true;">
<input name="submit_button" type="submit" value="Submit" />
</form>
You can achieve this without disabling the button by using a nonce, however it is a bit more complex. Essentially, when the user requests the page that has the form that will be submitted, assign a unique id to that user's request (store it somewhere on the server, and make sure it's submitted along with the form). When the form is then submitted, look up the unique id to make sure it's not in process or already processed, and then if it's OK to proceed, mark the unique id as "in process", process the form, and then mark it as processed. If when you do the initial check and the page is in process or already processed, you'll need to take the necessary action (redirect them to a confirmation page if it was successfully processed, or back to the form if it was not successfully processed).
How can I do this?
You can take a look at the javascript code in this page:
http://www.codinghorror.com/blog/archives/000096.html
<input type="Button" onClick="this.value='Submitting..';this.disabled=true;" value="Submit">
Can you please suggest any other technique to achive this goal without disabling the button?
Show a busy panel:
"... Your request is being processed please wait..."
(source: vodafone.co.uk)
If you disable a button right before submitting, then the parent form will not be submitted. You need to disable the button after submitting. Best way it to use JavaScript's setTimeout() function for this.
<input type="submit" id="foo" onclick="setTimeout('document.getElementById(\'' + this.id + '\').disabled=true;', 50);">
50ms is affordable enough to give the form the chance to get submitted.
To enhance the user experience more, you could of course append a message or a loading image dynamically during the same onclick event as already suggested by others.
Assuming you don't want to disable the button you could always pop up a modal on the page. This will block the user's interaction with the page. You could throw some kind of loading spinner in there with a message that the submit is in progress.
I don't understand why it is a problem, as you are doing a regular submit, the user should see a white page while you are processing in the back end.. But in case if you want to disable the button, here is the code, use it on the button
onclick="this.disabled=disabled"
You could have the button be disabled, but still seem active to the user. In the function that gets called after the button is hit the first time, have the first thing it does set a global variable like disableButton to true. When the user presses the button, have that go to a function called something like checkSubmitStatus. If disableButton = true, return false. if disableButton = false, trigger the submit function.
You have still disabled the button, but your users can press away unaware.
I'm not submitting anything, but Google Chrome 31 doesn't update the button look while calculating, so i came up with this workaround:
<style>
.btnMenu{width:70px; font-size:12px}
.btnMenu:disabled{background-color:grey}
</style>
<input type="button" class="btnMenu" value="Total" onmousedown="b=this; b.disabled=true; b.v=b.value; b.value='Calculating...'; setTimeout('updateTotals(); b.value=b.v; b.disabled=false', 100)"/>

Categories

Resources