Calling Javascript on a form post to update UI via jQuery - javascript

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.
});
});

Related

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...
}

How to iterate each form of same class and handle submits uniquely with jQuery?

I have multiple forms on the same page with the class form_delete.
How do I iterate over those forms in jQuery adding a submit event that will uniquely apply to each form?
I've tried this using $('.form_delete').each(...); but when I add $(this).submit(...) events it's not working (event does not register).
Forms:
<form class="form_delete">
</form>
<form class="form_delete">
</form>
<form class="form_delete">keep adding n forms to infinity ;)
jQuery:
$('.form_delete').each(function() {
$(this).submit( function(event) {
// Nothing gets registered here
});
}
$('.form_delete').each(function() {
$(this).on("submit", function(e) { // submit button pressed
// prevent form from doing what it normally does when submit button is pressed
e.preventDefault();
// do anything else that you want to do when the submit button is pressed
alert( "Hi");
});
});
jQuery's event delegation is also an option.
$('body').on('submit', '.form_delete', function submitCB(e) {
e.preventDefault();
});
When the event bubbles up to the body then jQuery will check the target element against the string selector (parm 2), and only call the callback (parm3) if it matches.
This way you only have on event listener on the page, as opposed to many.
I don't know why you use .each(); anyway if all forms with same class just use
$('.form_delete').on('submit',function(e){
e.preventDefault();
alert($(this).index());
return false;
});
in that case you will need something like data-selectForm to define which form you submited
<form class="form_delete" data-selectForm="firstform">
</form>
<form class="form_delete" data-selectForm="secondform">
</form>
and then use
$('.form_delete').on('submit',function(e){
e.preventDefault();
alert($(this).data('selectForm'));
return false;
});

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/

onsubmit refresh html form

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')
});

Categories