Why won't this form submit with AJAX? - javascript

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.

Related

How can I run onclick event from the assigned variable?

I've got a different scenario of a submit button - submit the info if the response is correct, and throw an error if the response is incorrect.
First, I store the submit button onclick event in a variable and make it null, so it will not submit the info if the response is incorrect.
Here is my code:
(function() {
var submitBtn = jQuery('#submitConfigBtn')[0]
var submitBtnOnclick = submitBtn.onclick
submitBtn.onclick = null
jQuery('#submitConfigBtn').click(function() {
var btn = jQuery(this);
...ajax call,
success: function(response) {
if (response === 'badresponse') {
console.log('Bad response')
} else {
console.log('Response is ok')
btn.onclick = submitBtnOnclick
btn.click();
}
},
err: function(err) {
console.log(err)
}
});
})
})()
How I can retrieve the event from the variable and run it inside the onclick function?
From what I understood, you want to submit the form if the response is okay. No need to store the onclick event just to stop the form from submitting, you can either use: event.preventDefault(), or use type="button" instead in your button
I used the latter here, so instead of invoking the click event of the button, you need to use .submit() to the form, like this:
$(function() {
$('.submitConfigBtn').on('click', function() {
//ajax part here
//sample response result
let response = 'badresponse';
if (response === 'badresponse') {
console.log('Bad response')
} else {
console.log('Response is ok')
$('.sampleForm').submit();
}
})
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form class="sampleForm" action="" method="POST">
<button type="button" class="submitConfigBtn">Submit Config Button</button>
</form>
I would suggest you do some tricky logic.
Step 1.
Use two button
1. Submit type
2. Button type
Step 2.
Hide the submit button always.
Step 3.
if(response == true){
$("submitbtnid").trigger('click');
}
else {
console.log('write your custom logic');
}
If you want to avoid the "standard action" to happen you can call event.preventDefault() inside your click-handler function. There is no need to delete and re-install the on-click function itself.
Furthermore the jquery element btn will not know what to do with the property "onclick". This would be a property of a DOM object.
You are not the first person to come up with this problem ;-)
See here https://stackoverflow.com/a/14154017/2610061 for a possible solution.
(It looks like you have to know which action you want to defer, as there is no standard way of belatedly triggering any action that was initially prevented from happening. You can only trigger specific actions like .submit() of a form.)
I prepared a scenario that would work for your requirements. Please note that I do not capture the "click" event on the actual button but instead I listen for the "submit" event on the surrounding form. The form can be submitted by either clicking the button or by hitting the return key after filling out the input field. The current event handler will be executed in either case!
At first the default action is prevented from happening, then an asynchronous Ajax call is sent. Its success function in .done() carries out some "meaningful" test on the response and - depending on its outcome - will then trigger the form's submission or not. Should the Ajax call itself fail the .fail() function jumps into action and will do whatever is required ...
$(function() {
$('.validatedForm').on('submit', function(ev) {
ev.preventDefault(); // prevent submission before AJAX call
$.getJSON('http://jsonplaceholder.typicode.com/users/'+$('#q').val())
.done(function(da){
console.log(da);
if (da.address.city!=="Howemouth") { // some meaningful test on the result ...
setTimeout(()=>ev.target.submit(), 3000); // belated form submission!
console.log('Hey, the input was changed, in 3 seconds I will go to google!')
}})
.fail(function(da){console.log(da.status, da.statusText,'- Only user-IDs 1 ... 10 are allowed.');});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="http://google.com" class="validatedForm">
<input name="q" id="q" value="7">
<button>submit</button>
</form>

jQuery click event first then follow url

I want to call a click event and then follow the href url.
HTML Link:
<a class="autoSave" href="?year=2013&week=42">←</a>
JS:
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('.submitForm').click(); //HTML Form that I'm wanting a submit to happen
window.location = $(this).attr('href');
});
});
The code above will just follow the url and not submit the form. If I omit the window.location call, the submit works.
You don't wait for the .click() event to be fully handled to call window.location.
You should serialize your form, post it by ajax (with .post() for instance), and then, in the callback of the .post(), change your page :
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
var serializedData = $('#yourForm').serialize(); //For example
$.post('your/path/to/form/validator', serializedData, function(){
window.location = $(this).attr('href');
});
});
});
You can't do a form submit without the browser trying to follow the form action. You need to use ajax to post your autosave data to your submit form and then do the window redirect when the ajax return successfully.
$('.autoSave').click(function(event){
event.preventDefault();
$.ajax({
url: "whatever your submitForm.click() file is",
type: "POST",
data: {
formField: theValue
anotherFormField: theValue,
},
success: function( data ) {
window.location = $(this).attr('href');
}
});
}
The problem is that the browser doesn't wait until the for m submission is done before it unloads the page and follows the link.
I'd recommend moving the location redirection to the end of your form submission:
$('.autoSave').on('click', function(event){
event.preventDefault();
$('.submitForm').triggerHandler('submit', [$(this).attr('href')]);
});
$('.submitForm').on('submit', function(event, url) {
// Do the thing
window.location = url;
})
Give your form an id and use the submit() function to submit it. Use a jQuery selector on the ID instead of a class, especially if you recycle the class you gave it.
HTML
<form id="submitForm">...</form>
Javascript
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('#submitForm').submit();
window.location = $(this).attr('href');
});
});
If your form is a standard form, the easiest thing to do is set a hidden input field value to the followup url:
$(document).ready(function() {
$('.autoSave').click(function(event){
event.preventDefault();
$('#redirectUrl').val($(this).attr('href'));
$('.submitForm').click(); //HTML Form that I'm wanting a submit to happen
});
});
In this scenario, you will have to have full control of the server side and you will be able to test for that value and do a 301.
This is far from ideal. There are a lot of options, but almost all of them are hackish in order to double-post from a single event.

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

How to remove a live submit event in jQuery?

I have two forms on our site #footer_leads and #footer_leads2 and i have a live submit event but need to verify a few things before the form gets summitted so i have this code
$('#footer_leads2, #footer_leads').live('submit', function(e){
e.preventDefault();
console.log('again');
var form = $(this); //save reference to form
if(somevalidation){
form.die();
form.submit(); //submit form
}
I assumed the jQuery die event would do the trick like in the above example but the page just into an infinite loop and crashes my browser....any ideas on how to do this
From the jQuery die() page:
Note: In order for .die() to function correctly, the selector used
with it must match exactly the selector initially used with .live().
Try $('#footer_leads2, #footer_leads').die() instead.
You shouldn't need to remove the handler and resubmit. Just wait on the preventDefault() until you know whether or not the form passed validation:
$('#footer_leads2, #footer_leads').live('submit', function(e) {
if (!somevalidation)
e.preventDefault();
// Else, the form will continue submitting unimpeded.
});
Are you want to disable the form after the submit?
if yes, try this:
$('input[type=submit]', this).attr('disabled', 'disabled');
I hope its help,
Don't unbind/die.
Just submit the form with the native method.
$('#footer_leads2, #footer_leads').live('submit', function() {
if (true /* validation succeeded */ ) {
this.submit(); //submit form, but don't use jQuery's method
} else {
return false;
}
});
UPDATE:
Since it sounds like you're making an AJAX call for the validation, you could just do the this.submit() in the success: callback.
$('#footer_leads2, #footer_leads').live('submit', function() {
$.ajax({
url: 'some/path',
context: this, // set the context of the callbacks to the element
...
success: function( d ) {
if( d.is_valid ) {
this.submit();
} else {
// give some feedback to the user for validation failure
}
}
});
return false; // block the submit by default
});
From the docs ( http://api.jquery.com/die/ ) :
Note: In order for .die() to function correctly, the selector used
with it must match exactly the selector initially used with .live().
You need to use .unbind('submit')

how can i close my jquery ui dialog when i submit a form?

i load a form into a jquery ui dialog. i have a submit button (inside my form - NOT the actual dialog buttons) that calls a controller action but i can't figure out how to close the dialog after the submit is called as i dont have any event handler that i am attaching.
is there anyway of doing this besides changing the submit to input type=button?
i know in jquery i can capture the submit
$('#positionForm').submit(function () {
// do stuff
return true;
});
but this seems to fire before submitting so i dont want to close the dialog yet.
is there anything wrong with the below code:
$('#positionForm').live('submit', function () {
$.post('/MyController/Action', $("#positionForm").serialize(), function (data) {
alert(data);
}, "html");
closeModalPopup();
return false ;
});
For updated question: You can call the close code in the success callback, like this:
$('#positionForm').live('submit', function () {
$.post('/MyController/Action', $(this).serialize(), function(data) {
$('#positionForm').closest(".ui-dialog-content").dialog("close");
}, "html");
return false;
});
Original Answer: You can attach a form submit handler, for example:
$("#myform").submit(function() {
$(this).closest(".ui-dialog-content").dialog("close");
});
You can give it a try here.
You can also do it using $("#name_of_the_dialog").dialog("close");
It's more natural than using $closest

Categories