XHR call using plain JavaScript - 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).

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)"/>

Disable Button Call Server then Re-enable Button

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>

Javascript Console Commands Not Working After Ajax Sending Back in Page

I'm controlling a website in Chrome developer console. There is a form and a submit button for sending the form via ajax (I guess) without refreshing the page. The form is resetting after sending information.
I assigned some attributes to a form element in the page with Javascript. There are some processes that do not matter, and I'm sending the form but the attributes of the elements are resetting in the new form. I am forced into calling the same scripts again.
Is there anyway for global valid command with console coding, because the webpage isn't mine? (In pure-JavaScript)
there are a couple ways to achieve this.
the easiest: will probably be to create a snippet in the web developer tools, and run it from there.
Another manner would be to create a google extension (with 'declarativeContent' and 'activeTab' permissions) that can inject content script or execute script on a page.
you can find more information on developing chrome extensions and background page events here: https://developer.chrome.com/extensions/background_pages
While using the form in a html page the values inside the form get submitted to the url given in the form action without checking the javascript if some callback functions are defined.
<form method="post" action="your_url">
....
</form>
If you doesn't provide the action then the form get submitted to the same page, and no javascript action will take place.
If you want to submit the form using the javascript action then you can use one of the following methods.
Method 1: Calling javascript function from action
<form method="" action="Javascript:your_function()">
....
</form>
<script>
function your_function(){
...
}
</script>
In this method all the form validation and ajax submission should be carried out manually inside the function. URL and METHOD should also be defined inside the ajax call.
Method 2: Using JQuery form onSubmit
<form id="target" method="" action="">
....
</form>
<script>
$( "#target" ).submit(function( event ) {
event.preventDefault();
alert( "Handler for .submit() called." );
});
</script>
In this method the form validation is handled and callback to submit function will take place only when the form is validated. The ajax url should be given inside the ajax call.
Method 3: Using JQuery Ajax Validation Submit
<form id="target" method="post" action="your_url">
....
</form>
<script>
$("#target").validate({
submitHandler: function(form) {
$(form).ajaxSubmit({
dataType: 'json', //optional
success: function(data) {
...
}
})
}
})
</script>
In this method the URL and METHOD are defined in the form. The validate function will check whether the form is valid and submitHandler will execute when the form is valid. $(form).ajaxSubmit callback function will handle the ajax call to the URL and METHOD given the the form. This method will well suit for your question. Also try other methods in you need so
NOTE: Refer https://jqueryvalidation.org/validate/ for documentation.
Remove any submit listener on the form. Then attach your own submit listener with js event.stopPropagation() break.

javascript form.submit() losing querystring created by GA _linkByPost

We have a booking form that POSTs to the parent company website. Because this is a different domain we need to implement the GA _linkByPost to pass the GA tracking cookie info across domains.
As the booking form is in a .NET user control it does a postback. On postback we validate, wrap up the booking info, and write a form back to the client with hidden elements required by the target booking engine and add line of javascript to submit the form.
Below is the javascript function I'm using to submit the form:
function postBookingForm() {
var thisForm = document.getElementById('PostForm');
_gaq.push(['_linkByPost', thisForm]);
thisForm.submit();
}
And the relevant form info:
<form id="PostForm" name="PostForm" action="ClientBookingEngineUrl" method="post" >
booking form info in here
</form>
The result is that we fill in the form, hit submit which does a round trip to the server generates a new form and POSTs the info. This all works fine apart from the URL loses the GA cookie info from the query string. If I comment out the form submit line and look at source code I can see the GA cookie info on the querystring - but when posting, I do not see the querystring (using Fiddler).
To clarify:
The above technique works and does what we want with regards to POSTing form data to the booking engine and taking the user there.
If the submit line is commented out you can see the form with the modified action that has the GA stuff appended (using Firebug).
If the form is submitted with the submit line, the querystring info is removed (confirmed by Fiddler).
Am I missing something obvious? Are there some gotchas regarding JS submit, form POSTs and querystrings? Or is there a simple trick I'm missing?
Cheers
EDIT 1
An oddity has occured.
If I alert the form action before and after the _gaqPush then we can see the URL in its before and after state and it's as expected.
alert('1 form action = ' + thisForm.action);
_gaq.push(['_linkByPost', thisForm]);
alert('2 form action = ' + thisForm.action);
Alert 1 shows the pre-modified action and alert 2 shows the action with the GA info.
With the alerts in place it submits WITH the GA info in the query string.
If I comment out the alerts the GA info is NOT in the query string...
I'm starting to think the form or something is not ready so I'm trying it with JQuery's document ready.
EDIT 2
Wrapping the method call in document ready doesn't help. I'm confused as to why action URL is correct AFTER displaying it in an alert but incorrect if I don't alert it.
Answering this for posterity.
The problem is the _qaq (Google Analytics Queue) hasn't had time to modify the form before the call to submit() the form.
The solution is to push a function onto the _gaq object that submits the form so it will happen directly after the form modification is done.
function postBookingForm() {
var thisForm = document.getElementById('PostForm');
_gaq.push(['_linkByPost', thisForm]);
_gaq.push(function() { thisForm.submit(); });
}
I tried a simple HTML page that calls _gaqPush and submits immediately. This also fails.
Adding a 1000ms delay works (for the most part) so I suspect the alerts just gave the GA script time to modify the form.
I'm closing/accepting this as it seems down to submitting the form too quickly after the GA call.

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