onsubmit refresh html form - javascript

I'm trying to use Javascript to submit the form's data. Here's the html.
<form onsubmit="post();">
//input fields here
</form>
Here's the Javascript for the post() function.
var post = function() {
alert('the form was submitted');
return false;
}
My issue is that the Javascript runs but the form still processes and refreshes the page..
I put the return false; code in hoping it would stop the form from refreshing.

You will have to put the return false part after the post() function in the onsubmit handler, like so:
<form onsubmit="post();return false;">
//input fields here
</form>

Keep your js out of the DOM.
<form id="myform" action="somepage.php" method="post">
//input fields
</form>
JQuery:
$('#myform').submit(function(event){
alert('submitted');
event.preventDefault();
});

You need to actually return false from your inline dom-0 handler. So change
onsubmit = "post();">
to
onsubmit = "return post();">
Or you could give your form an id and do this:
<form id="form1" onsubmit = "post();">
Then from a safe location in which your dom is ready:
document.getElementById("form1").onsubmit = post;

Since you added the jQuery tag, this it the best way to do this:
unobtrusive event attach
$('form').submit(function(){
alert('the form was submitted');
return false;
});
In your's way it should be;
<form onsubmit="return post();">

Since this post is tagged with jQuery, I'll offer the following solution:
$('form').submit(function(e){
//prevent the form from actually submitting.
e.preventDefault();
//specify the url you want to post to.
//optionally, you could grab the url using $(this).attr('href');
var url = "http://mysite.com/sendPostVarsHere";
//construct an object to send to the server
//optionally, you could grab the input values of the form using $(this).serializeArray()
var postvars = {};
//call jquery post with callback function
$.post(url, postvars, function(response){
//do something with the response
console.log(response);
}, 'json')
});

Related

HTML/Javascript: Capture Form Response [duplicate]

I wanna write my own form validation javascript library and I've been looking on google how to detect if a submit button is clicked but all I found is code where you have to use onClick on onSubmit="function()" in html.
I would like to make this javascript so that I don't have to touch any html code like adding onSubmit or onClick javascript.
Why do people always use jQuery when it isn't necessary?
Why can't people just use simple JavaScript?
var ele = /*Your Form Element*/;
if(ele.addEventListener){
ele.addEventListener("submit", callback, false); //Modern browsers
}else if(ele.attachEvent){
ele.attachEvent('onsubmit', callback); //Old IE
}
callback is a function that you want to call when the form is being submitted.
About EventTarget.addEventListener, check out this documentation on MDN.
To cancel the native submit event (prevent the form from being submitted), use .preventDefault() in your callback function,
document.querySelector("#myForm").addEventListener("submit", function(e){
if(!isValid){
e.preventDefault(); //stop form from submitting
}
});
Listening to the submit event with libraries
If for some reason that you've decided a library is necessary (you're already using one or you don't want to deal with cross-browser issues), here's a list of ways to listen to the submit event in common libraries:
jQuery
$(ele).submit(callback);
Where ele is the form element reference, and callback being the callback function reference. Reference
<iframe width="100%" height="100%" src="http://jsfiddle.net/DerekL/wnbo1hq0/show" frameborder="0"></iframe>
AngularJS (1.x)
<form ng-submit="callback()">
$scope.callback = function(){ /*...*/ };
Very straightforward, where $scope is the scope provided by the framework inside your controller. Reference
React
<form onSubmit={this.handleSubmit}>
class YourComponent extends Component {
// stuff
handleSubmit(event) {
// do whatever you need here
// if you need to stop the submit event and
// perform/dispatch your own actions
event.preventDefault();
}
// more stuff
}
Simply pass in a handler to the onSubmit prop. Reference
Other frameworks/libraries
Refer to the documentation of your framework.
Validation
You can always do your validation in JavaScript, but with HTML5 we also have native validation.
<!-- Must be a 5 digit number -->
<input type="number" required pattern="\d{5}">
You don't even need any JavaScript! Whenever native validation is not supported, you can fallback to a JavaScript validator.
Demo: http://jsfiddle.net/DerekL/L23wmo1L/
This is the simplest way you can have your own javascript function be called when an onSubmit occurs.
HTML
<form>
<input type="text" name="name">
<input type="submit" name="submit">
</form>
JavaScript
window.onload = function() {
var form = document.querySelector("form");
form.onsubmit = submitted.bind(form);
}
function submitted(event) {
event.preventDefault();
}
Based on your requirements you can also do the following without libraries like jQuery:
Add this to your head:
window.onload = function () {
document.getElementById("frmSubmit").onsubmit = function onSubmit(form) {
var isValid = true;
//validate your elems here
isValid = false;
if (!isValid) {
alert("Please check your fields!");
return false;
}
else {
//you are good to go
return true;
}
}
}
And your form may still look something like:
<form id="frmSubmit" action="/Submit">
<input type="submit" value="Submit" />
</form>
If you have multiple forms in same page & you wants to handle submit event Listener without using Id
jQuery
$('form').submit(function (event) {
targetObj = event.target;
// do your logic
});
Pure JavaScript trick
Onload just do below way.
for(var i=0; i<document.forms.length; i++){
var form = document.forms[i];
form.addEventListener("submit", myListener,false);
}
credit :- Multiple Form Submit Event Listener Handling using JavaScript credit goes to Jan Pfeifer's Answer on StackOverflow Community
I hope this helps to someone
With jQuery:
$('form').submit(function () {
// Validate here
if (pass)
return true;
else
return false;
});

Why won't this form submit with AJAX?

I'm trying to submit a form to Campaign Monitor. They offer this code example to POST via Ajax.
This is my code for my multi-step modal.
var next_step = false;
var final_step = false;
$('.next').on('click', function(e){
e.preventDefault();
if (next_step) {
$('#step-1').slideUp(function(){
$('#step-2').slideDown();
$('.next').html('Submit');// Change button text to submit
final_step = true;
});
}
next_step = true;
if (final_step) {
$('#myform').submit(function (e){
alert('submit started'); //This never fires unless I remove the preventDefault();
e.preventDefault();//But if I remove this, the page will refresh
$.getJSON(
this.action + "?callback=?",
$(this).serialize(),
function (data) {
if (data.Status === 400) {
alert('error');
} else {
alert('success');
}
})
});
}
});
On the last step of the form, I check whether final_step is true, if so, go ahead and submit the form via ajax.
The problem is that it just doesn't do anything? But if I remove the e.preventDefault(); from the $('#myform') it will post the form as normal and re-direct you to the form URL.
How can I fix this?
What you are doing currently is wiring up an onsubmit handler. Not invoking submit.
$('#myform').submit(function (e){ });
...is the same thing as...
<form action="#" method="post" onsubmit="return someFunction()">
... which is the same as ...
$('#myForm').on('submit', function(e){});
You are never submitting the form.
What you are looking for is to use Ajax to post the data to the server and not submit the form.
You can do that like this:
$.ajax({
type: "POST",
url: "SomeUrl.aspx",
data: dataString,
success: function() {
//display message back to user here
}
});
dataString would be replaced with the values you posting.
$('#myform').submit(function (e){
just registers an event handler and attaches it to the "submit" event of "myform", it doesn't actually cause a submit. It means you're saying you'd like this function to be run every time the form is submitted. This handler function should be outside your $('.next').on('click', function(e){ block. Just below it will do.
If, within the $('.next').on('click', function(e){ block you wish to cause the form to be submitted, write:
$('#myform').submit();
This will actually trigger the form submission.
See https://api.jquery.com/submit/ for more info on what the different method signatures of "submit" actually do.
This line: $('#myform').submit(function (e) { registers the function you pass as an argument as a handler to the submit event of the form, and does not invoke a submit action. I'm not sure whether or not this is the problem, though I would recommend preventDefault() outside of the wizard flow
(e.g.
$(document).ready(function() {
$("#form").submit(function(e) {
e.preventDefault();
}
});
)
Then inside the if(final_step) just do the post without worrying about the form.
Also, you'd do good in not setting a submit button inside the form if you do not wish to use it's functionality. Just create an element with a click event that sends the data rather than registering to the submit event of the form.
I'm not sure but I always do $('#form').submit() after click in element and catch this event (e.g. by $('#form').on('submit', function () { .. });) in other place.

How to disable html form from navigating on submit?

Lets say I have this form
<form onsubmit="submitData();">
<input type="text" pattern="^[A-z]+$" required>
<button type="submit">OK</button>
</form>
Upon clicking the submit button, I don't want the form to post any data in the address bar or navigate anywhere, I just want it to run the submitData function and thats it. The reason I want to use the form is because of its validating functionality (it wont let you submit if the input text is missing or doesn't match the pattern).
If I switch the value of onsubmit on the form to "return false;" then it won't navigate but "submitData(); return false;" doesn't work. Any other ideas?
Try adding e.preventDefault(); at the beginning of your code, with the event being passed to your function submitData(e) {, like this:
function submitData(e) {
e.preventDefault();
...
}
See: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Just add event.preventDefault that is automatically pass by the form to the function:
function submitData(event){
event.preventDefault();
//your code will be here
}
read more : https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
Use event.preventDefault().
Learn more: https://developer.mozilla.org/en/docs/Web/API/Event/preventDefault
add this to your code:
document.getElementById("addYourTagHERE").addEventListener("onsubmit", function(event){
event.preventDefault()
});
or this in your function:
function submitData(event) {
event.preventDefault();
}
You'd want to cancel the default action of the submit event handler, so:
function submitData() {
// whatever logic you have...
return false;
}
I believe this works too:
function submitData( e ) {
e.preventDefault();
// whatever logic you have...
}

Calling Javascript on a form post to update UI via jQuery

I have an Input element that submits a form:
<input type="submit" value="Download" id="downloadButton" class="btn-download" />
I need the button to call a javascript function, and then post the form normally.
How would that be done in jQuery?
$('#downloadButton').on('click', function (e) {
e.preventDefault();
//call your function here
$(this).parents('form').submit();
});
the preventDefault() call is important because it stops the submission of the form so you can call your function before the form submit is called at the end.
You can do:
<form onsubmit="return doSomething();">
</form>
function doSomething() {
// do something
return true;
}
If in the doSomething function you don't like what you're seeing, then return false instead of true.
EDIT
The jQuery equivalent (to satisfy both commenters): remove the onsubmit from the HTML and replace with:
jQuery(document).ready(function () {
jQuery("form#myFormId").submit(doSomething);
});
Take a look at this jsfiddle
It changes the case of textbox content to to upper case before submitting the form
$('#formID').on('submit', function () {
//var form = $(this),
//input = form.find('input[type="text"]');
//input.val(input.val().toUpperCase());
//alert(input.val());
// call your function here!
});
this is what you request:
1.- click a button (adding event handler)
2.- call a function
3.- submit form
myfunction(){
//do wathever you want
$('#formid').submit();
}
$(document).on("click", "#downloadButton", myfunction);
you can do also:
$(document).on("click", "#downloadButton", function(event){
$('#formid').submit();
});
without having an extra function
but the solution of #Paritosh is the more accurate.
jsFiddle here
Change input type to type="button" and use:
$('#downloadButton').click(function() {
//Do any javascript stuff here
//And here, etc. Then, when ready...
$('#yourFormID').submit();
});
I recommend assigning an ID attribute to your form as it is good practice.
<form id="yourFormID" action="" method="POST">
Perhaps you have only one form on this page, in that case $('form').submit() is fine. But in future (or perhaps even on this page, you haven't said) you may have multiple forms on a page and therefore the ID is necessary to specify the exact form to be submitted.
Note that if you do NOT change the submit button element's <input type="submit" to <input type="button", then you must use e.preventDefault() to prevent the button's default action. Why bother with that? Just change type="button" and use less code and less future confusion.
add a submit event on form.
$('form').submit(function(event){
event.preventDefault();
var formObj = $(this);
var formData = formObj.serialize();
$.ajax({
type: 'post',
data: formData
}).done(function(response){
console.info(response);
// update UI here accordingly.
});
});

Jquery validator valid status with ajax submit

I am trying to post a form using ajax after a form has been validated. However the .valid seems to be wrong.
Multiple action type is desired based on button.
This example is also not showing the errors messages correctly upon submit
$('#submit').click( function(){
alert(validator.valid());
});
$('#submit2').click( function(){
alert(validator.valid());
//do something else
});
status become true if i enter a required field (e.g name)
this is the fiddle
try this fiddle
http://jsfiddle.net/r2HUu/4/
It's working. I just checked form' validation by $("#myForm").valid()
Quote OP:
"I am trying to post a form using ajax after a form has been validated"
As per documentation, your ajax goes inside the submitHandler callback function.
submitHandler (default: native form submit) Type: Function()Callback
for handling the actual submit when the form is valid. Gets the form
as the only argument. Replaces the default submit. The right place to
submit a form via Ajax after it validated.
Using this callback, the click is captured automatically and the function is only fired on a valid form.
$(function () {
var validator = $("#myForm").validate({
// rules and options,
submitHandler: function(form) {
// your ajax goes here
alert("valid form");
return false;
}
});
});
DEMO: http://jsfiddle.net/fXDwd/
Quote OP:
"However the .valid seems to be wrong."
EDIT
As per OP's comments and updated jsFiddle:
If you want to have multiple submit buttons do different things on one form, construct click handlers for each button which you've already done. Now you must move those buttons to outside of the <form></form> container. Otherwise, the plugin will treat them both as normal submit buttons and interfere with your click handlers.
The other problem is your implementation of .valid(). Attach it to the form element, $("#myForm"), not the validator initialization object.
HTML:
<form id="myForm" action="">
...
</form>
<input type="button" id="submit" value="Submit form" />
<input type="button" id="submit2" value="Submit form2" />
jQuery:
$(function () {
var validator = $("#myForm").validate({
// rules and options
});
$('#submit').click(function () {
alert($("#myForm").valid());
//do something
});
$('#submit2').click(function () {
alert($("#myForm").valid());
//do something else
});
});
DEMO: http://jsfiddle.net/vfrGU/

Categories