Prevent submit on a jQuery form - javascript

I'm setting up a password control on a login form with jQuery and ajax.
So far, this is the script
$(document).ready(function() {
$("#login-form").submit(function(e) {
var csrftoken = getCookie('csrftoken');
var password = $('#login-password').val();
var email = $('#login-email').val();
$.ajax({
url: "/password_check/",
type: "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: csrftoken,
password: password,
email: email
},
success: function(result) {
document.getElementById("login-error").innerHTML = result.response;
event.preventDefault();
}
});
return false;
});
});
With this, the error gets caught when firing the submit button, but if the password is correct the submit doesn't work (even though the error doesn't show up anymore).
What am I missing?

You have an asynchronous ajax call, so by the time your success function fires, the form submit event has passed so you need to submit the form again but use the DOM method, which will bypass the jQuery event handler and allow the form to submit.
success: function(result) {
if(result == "correct"){
document.getElementById("login-form").submit();
} else {
document.getElementById("login-error").innerHTML = result.response;
}
}
As you didnt say what response indicates a correct password, I have used result == "correct", so change that accordingly.

You have to return false only if u dont want to submit the form.
If password is correct you need to return true in your case.

Related

Dual submission of form creating issue with validation

my forms have dual submission.
Step 1. submission on my defined url with ajax
Step 2. allow form to behave as its default behavior.
Issue:
I am not providing any validation with my script. i am not using any plugin like jquery validate.
when submitting the form, the jquery validation is working (Which is if form already heve) but just after the ajax complete it is allow to submit the form.
That should not happens if validation is there.
I am providing this my script to my client to get the submitted form info in my platform.
Thats why i don't know which validation client will use or if they will not use or they will use any plugin for validation.
i just want to stop the submission if there is validation error..
I know there is issue with
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
return true;
Script part:
$("form[data-track=MySubmit]").on("submit", function(event) {
var formInputData = $(this).serialize();
$.ajax({
url: "/insertdata",
type: "post",
data: formInputData
dataType: 'json',
success: function(responce) {
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
return true;
}
});
});
more info :
its a double submission script..means first it will submit the form on one url which is not in form action then it will allow form to do its default behaviors like
Ist step to save the info using ajax on my url
and then in 2nd step if form have action to submit the form then do this or if form has ajax submission then do this or etc other form behavior on submit
Update :
There is 2 person
I am
My client
I am providing my form submission script to my client they have their own form to and own jquery/javascript.
So now i am giving them my script and asking to put it on your form with my way and once they will put , i will also get the detail of form after submit.
But I AM NOT PROVIDING ANY SCRIPT FOR VALIDATION..
they have own validation there could be any plugin or custom jquery/javascript.
My issue :
How can i stop form submission if there is validation from their form's own jQuery/Javascript ?
Inside Ajax Success function check again for form valid
if($("form[data-track=MySubmit]").valid()){
// the form is valid, do something
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
} else{
// the form is invalid
}
You can try
event.preventDefault();
Like this
$("form[data-track=MySubmit]").on("submit", function(event) {
var formInputData = $(this).serialize();
$.ajax({
url: "/insertdata",
type: "post",
crossDomain: true,
data: formInputData
dataType: 'json',
success: function(responce) {
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
}
});
event.preventDefault();
});
You can use jquery validate() method for this. we can pass submitHandler function which handles how the form submit is handled after form is found to be free of client side validations.
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 is validated.
Example: Submits the form via Ajax when valid.
$("#myform").validate({
submitHandler: function(form) {
$(form).ajaxSubmit();
}
});
You can try this :
$("form[data-track=MySubmit]").validate({
submitHandler: function(form) {
var formInputData = $(form).serialize();
//the default form submit behaviour
$(form).submit();
//form submit via ajax on custom url
$.ajax({
url: "/insertdata",
type: "post",
data: formInputData
dataType: 'json',
success: function(response) {
console.log('form is submitted');
}
});
}
});
You can try return false and event.preventDefault both at the same time + You can change the behavior of code when the forms return true.
dataCheck = false;
$("form[data-track=MySubmit]").on("submit", function(event) {
if(dataCheck === false)
{
event.preventDefault();
var formInputData = $(this).serialize();
$.ajax({
url: "/insertdata",
type: "post",
data: formInputData,
dataType: 'json',
success: function(responce) {
dataCheck = true;
$("form[data-track=MySubmit]").off("submit");
$("form[data-track=MySubmit]").trigger( "submit" );
return true;
}
});
return false;
}
});
try this
for validation you can use JQuery Validation Engine Plugin here:https://github.com/posabsolute/jQuery-Validation-Engine
$("form[data-track=MySubmit]").submit(function(event) {
event.preventDefault(); /////////added
var formInputData = $(this).serialize();
$.ajax({
url: "/insertdata",
type: "post",
data: formInputData, //////missing comma
dataType: 'json',
success: function(responce) {
$("form[data-track=MySubmit]").submit();
}
});
});
From what I understand, you want to submit your form with AJAX to url, where the validation happens and if it returns successfully, submit it a 2nd time to its default action.
If this is the case, then your code almost works, but you need to do two things:
Put event.preventDefault(); in your submit handler to prevent at the beginning the default action of the form, because we want us to trigger it only after AJAX returns successfully.
If AJAX returns successfully and you see that your form is not submitted a 2nd time, make sure that your form does not have a submit button named "submit", because that would hide the default submit action and $("form[data-track=MySubmit]").trigger( "submit" ); would not work! Rename your submit button to "submitBtn" or whatever.
BTW, you are missing a comma after data: formInputData
Have a hidden button with "default" submit. Once you are done with your processing ajax using jQuery, invoke the click event on the button.

submit form with ajax validation jquery / standard javascript

I'll start with an apology - I'm a .NET coder with little (no) front-end experience.
When the user clicks on Submit, the form needs to call a REST service, if the service returns true then the user is presented with a warning that a duplicate exists and are asked whether they want to continue. Appreciate any help.
I have the Submit button ONCLICK wired up to Approve()
When the checkForDuplicateInvoice() gets called, it passes the control back to the calling function right away before the ajax call has a chance to get the result. The effect is that the Validate() function finishes without taking into account whether or not a duplicate invoice exists.
I need help in modifying the form so that when the user clicks on the submit button, the form validates (including the ajax call to the db) before finally submitting.
I've modified the code based on Jasen's feedback.
I'm including https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js in my header.
The error I get now is "Object doesn't support property or method 'button'"
What I have now for my form submission/validation is:
$(document).ready(function () {
$("#process").button().click( function () {
if (ValidateFields()) { // internal validation
var companyCode = document.getElementById("_1_1_21_1").value;
var invoiceNo = document.getElementById("_1_1_25_1").value;
var vendorNo = document.getElementById("_1_1_24_1").value;
if (vendorNo == "undefined" || invoiceNo == "undefined" || companyCode == "undefined") {
return false;
}
$.ajax({ // external validation
type: "GET",
contentType: "application/json;charset=utf-8",
//context: $form,
async: false,
dataType: "jsonp",
crossDomain: true,
cache: true,
url: "http://cdmstage.domain.com/services/rest/restservice.svc/CheckDuplicateInvoice?InvoiceNumber=" + invoiceNo + "&VendorNumber=" + vendorNo + "&CompanyCode=" + companyCode,
success: function (data) {
var result = data;
var exists = result.CheckForInvoiceDuplicateResult.InvoiceExists;
var valid = false;
if (exists) {
if (confirm('Duplicate Invoice Found! Click OK to override or Cancel to return to the form.')) {
valid = true;
}
}
else {
valid = true; // no duplicate found - form is valid
}
if (valid) {
document.getElementById("_1_1_20_1").value = "Approve";
doFormSubmit(document.myForm);
}
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
});
});
First review How do I return the response from an asynchronous call? Understand why you can't return a value from the ajax callback functions.
Next, disassociate the submit button from the form to prevent it from performing default submission. Test it to see it does nothing.
<form>
...
<button type="button" id="process" />
</form>
Then wire it up to make your validation request
$("#process").on("click", function() {
if (valid()) {
$(this).prop("disabled", true); // disable the button to prevent extra user clicks
// make ajax server-side validation request
}
});
Then you can make your AJAX request truly asynchronous.
$.ajax({
async: true,
...,
success: function(result) {
if (exists) {
// return true; // returning a value is futile
// make ajax AddInvoice call
}
}
});
Pseudo-code for this process
if (client-side is valid) {
server-side validation: {
on response: if (server-side is valid) {
AddInvoice: {
on response: if (successful) {
form.submit()
}
}
}
}
}
In the callback for the server-side validation you make the AddInvoice request.
In the callback for AddInvoice you call your form.submit().
In this way you nest ajax calls and wait for each response. If any fail, make the appropriate UI prompt and re-enable the button. Otherwise, you don't automatically submit the form until both ajax calls succeed and you call submit() programmatically.

Have to click submit twice for AJAX request to fire on form submission

My Form HTML looks like this.
<form novalidate action="register.php" method="post" >
<label for="username">Username</label>
<input type="text" name="username" required placeholder="Your username" autofocus/>
<input type="submit" name="register" value="Register" cid="submit" />
</form>
And My jQuery looks like this
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
e.preventDefault();
});
The sad thing is that it logs hello to the console but it never submits the form with one click on the submit button. I need to press two times to submit button.
Can anyone tell me the problem and how can I fix it so that 1 click is sufficient for form submission.
NOTE: The data of form is send for validation not actually for submission . If data like email , username etc are valid i want the form to be submitted with one click.
Try separating the validation from the form submit.
Simply changing this line:
$("form").submit(function(e) {
to
$("input[name='register']").click(function(e) {
First of all I think it would be cleaner to use a success function instead of a .done() function. For example:
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
// Merge the check.php and register.php into one file so you don't have to 'send' the data twice.
url: "register.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON",
success: function() {
console.log("This form has been submitted via AJAX");
}
});
});
Notice that I removed the .unbind() function, as I suspect it might be the reason your code is acting up. It removes the event handlers from the form, regardless of their type (see: http://api.jquery.com/unbind/). Also, I put the e.preventDefault() at the start. I suggest you try this edited piece of code, and let us know if it does or does not work.
EDIT: Oh, and yeah, you don't need to submit it when you're sending the data via AJAX.
Try this one.
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
});
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datatype: "JSON",
success: function(data) {
return data;
}
});
});
So, to break it down.
Stop the form submission with the preventDefault().
Get the form data and submit it to your validator script.
The return value, I assume, is a boolean value. If it validated, it'll be true, or false.
Return the value which will continue the form submission or end it.
NB.: This is a horrible way to validate your forms. I'd be validating my forms on the server with the form submission, because javascript can be terribly easily monkeyed with. Everything from forcing a true response from the server to turning the submission event listener off.
Once I have the same issue
What I found is I have some bug in my url xxx.php
it may return error message like "Notice: Undefined variable: j in xxx.php on line ....."
It may let ajax run unexpected way.
Just for your info.
Instead of doing prevent default when clicking a submit button, you can create a normal button and fire a function when you click it, at the end of that function, submit the form using $('#form').submit();. No more confusing prevent default anymore.
You don't need to call submit() since you are posting your data via ajax.
EDIT You may need to adjust the contentType and/or other ajax params based on your needs. PHP example is very basic. Your form is most likely much more complex. Also, you will want to sanitize any php data - don't rely on just the $_POST
jQuery:
$("form").submit(function(e) {
$.ajax({
'type': 'post',
'contentType': 'application/json',
'url': 'post.php',
'dataType': 'json',
'data': { formData: $(this).serialize},
'timeout': 50000
).done(function(data) {
// Response from your validation script
if (data === true)
{
// SUCCESS!
}
else
{
// Something happened.
}
).fail(function(error) {
console.log(error);
});
e.preventDefault();
});
PHP
$is_valid = FALSE;
$name = $_POST['name'];
if ($name !== '')
{
$is_valid = TRUE;
}
else
{
return FALSE;
}
if ($is_valid)
{
// insert into db or email or whatver
return TRUE;
}

Given a form submit, how to only submit if the server first responses back with a valid flag?

I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});

jquery ajax call taking too long or something

I have a form that I want to ensure the paypal email address is valid before I submit. So i am making a jquery submit call like this
$('#new_user').submit(function(){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
return true;
}
}
});
but the problem is this call thats a second and the page already refreshes before the ajax is complete....if I put the return false at the end of the call I can see my json is correct but for some reason the way I have it now wont finish...any ideas on how to correct this
Just use preventDefault() immediately when the submit event is fired. Then wait for the response from paypal and then call submit() on the form.
$('#new_user').submit(function(e){
e.preventDefault();
var form = $(this); //save reference to form
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
form.unbind('submit'); //remove binding
form.submit(); //submit form
}
}
});
If you want to do something right away you would need to set async false in the request

Categories

Resources