Submit a form generated by jquery - javascript

The login form on my site is shown using an overlay/modal with jquery-modal (http://kylefox.ca/jquery-modal/examples/)
I'm using ajax + php to validate the form. If validation passes, the form should be submitted.
I can halt the submit for validation (using return false), and the validation itself is working fine. But I don't know how to submit the form
I have tried many naive variations: return true, $theform.submit(), $("body").unbind("#myloginform") and more.. but so far no luck
$("body").on("submit", "#myloginform", function() {
$theform = $(this);
$.ajax({
url: "login_check.php",
type: "POST",
cache: false,
timeout: 9000,
data: $theform.serialize(),
dataType: "json",
success: function(data) {
if (data) {
if (data.status == "ok") {
alert("success! now the form can be submitted");
// SUBMIT THE FORM (instead of the alert)
} else {
$("body #loginstatus").html(data.status);
}
} else {
alert("Error bla bla.");
}
},
error: function(e) {
alert("Error (ajax) bla bla.");
}
});
return false;
});

To submit the FORM, you can call js native submit method:
document.getElementById('myloginform').submit();
See variants:
$('#myloginform')[0].submit();
$('#myloginform').get(0).submit();
An other way would be to set context option of ajax to this:
$.ajax({
context: this,
...,
});
And then in success callback, submit FORM using:
this.submit();
EDIT: i see you are already using a variable reference, so in your case, you can use too:
$theform[0].submit();
All these snippets won't trigger jQuery submit handler, avoiding a circular reference error.

Another approach:
var checkValid = false;
$("body").on("submit", "#myloginform", function () {
$theform = $(this);
if (!checkValid) {
$.ajax({
url: "login_check.php",
type: "POST",
cache: false,
timeout: 9000,
data: $theform.serialize(),
dataType: "json",
success: function (data) {
if (data) {
if (data.status == "ok") {
alert("success! now the form can be submitted");
// Everything is OK
checkValid = true;
$theform.submit();// Next time, no validation process, just natural send of the form.
} else {
$("body #loginstatus").html(data.status);
}
} else {
alert("Error bla bla.");
}
},
error: function (e) {
alert("Error (ajax) bla bla.");
}
});
return false;
}
});

Since you're using jQuery, I would suggest that you check out the jQuery submit function
http://api.jquery.com/submit/

Related

Delete record with jQuery and AJAX Delete not working

My problem is that when I press yes on delete confirmation the db record goes away, but if I refresh the page it comes back.
Maybe I have to put the language and the id inside the Ajax URL?
If yes how can I do this?
Please forgive me I am still learning.
This is for java eclipse and SQL database
var assetId;
var batchId;
function cancelOpname(){
$.ajax({
type: "POST",
cache: false,
url: urlPage + "opname/cancel",
dataType: "JSON",
data: data,
beforeSend: function() {
$('.loader').fadeIn();
},
complete: function() {
$('.loader').fadeOut();
},
success: function() {
if (data.errorResult == false) {
console.log("Success: else ");
javascript:window.history.back();
} else {
$('.loader').fadeOut();
}
},
error : function(e) {
console.log("ERROR: ", e);
}
});
}
no error but ajax and jQuery not working

jQuery $(this).closest("form").submit(); not executing

Can anyone please tell me why my submit is not being executed? The log tells me: "Validation passed, will submit form", but is not submitting?
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $("#ajax-payment-form").serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
// If a response is received from your server
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest("form").submit();
} else {
console.log(msg);
}
}).fail(function() {
console.log('AJAX error');
});
});
});
Thanks for your time
thar
just do this:
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
var $this = $(this);
e.preventDefault();
// Serialize data, make AJAX call
var str = $("#ajax-payment-form").serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
// If a response is received from your server
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$this.closest("form").submit();
//....
or shorter code: (Notice de submit event)
$(function(){
$("#ajax-payment-form").submit(function(e) {
e.preventDefault();
var $form = $(this);
$.post(
url: templateDir+"/payment_form/payment_process.php",
$form.serialize(),
function(){
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$form.closest("form").submit();
} else {
console.log(msg);
}
},
'json'
).fail(function() {
alert( "error" );
});
});
});

Ajax call multiple time onclick event on bootstrap modal

By clicking a button Its loaded a bootstrap modal. On the modal there have a form and on click save button I am trying to submit form by ajax call. At first time the ajax call trigger one time, but 2nd time the ajax url trigger two times. I see on firebug console section the post url is called multiple times.
Here Is my jquery code.
$(".show-modal").click(function() {
$('.upload-modal').modal();
$(".save-logo").click(function(e) {
e.preventDefault();
$.ajax({
type : "POST",
data : data,
contentType: false,
cache : false,
processData: false,
url : "../../io/upload/"
}).done(function(rawData) {
$('.modal-header .close').click();
})
});
})
The problem is that you have your .save-logo click handler inside the .show-modal click handler. So every time the modal is shown, you attach another click handler to the .save-logo element. The code below should fix that problem:
$(".show-modal").click(function () {
$('.upload-modal').modal();
});
$(".save-logo").click(function (e) {
e.preventDefault();
$.ajax({
type: "POST",
data: data,
contentType: false,
cache: false,
processData: false,
url: "../../io/upload/"
}).done(function (rawData) {
$('.modal-header .close').click();
})
});
$(function(){
var editUserId;
$('#edit-user-modal').on('show.bs.modal', function(e) {
editUserId = $(e.relatedTarget).data('userid');
});
$("#edit-user-form").submit(function(event) {
event.preventDefault();
var form = $(this);
var route = "/edit-user/" + editUserId;
if(validateEditUserForm()){
$.ajax({
type: "POST",
url: route,
data: form.serialize(),
success: function(Response)
{
if(Response){
console.log(Response.status);
console.log(Response.message);
if(Response.status == 'success'){
$('#adduser-alert-box').hide();
$("#add-user-form")[0].reset();
$('#adduser-success-box').show();
$('#adduser-success-box').html(Response.message);
}
else{
console.log('User could not be added');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html(Response.message);
}
}
else{
console.log('No Response');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('No Response');
}
}
});
}
else{
console.log('Validation Error');
$('#adduser-alert-box').show();
$('#adduser-alert-box').html('Please Fill All the Fields Correctly');
}
});});
I faced the same issue and randomly i tried something .
so if you create a global variable to store the 'id' you pass from your button then store the id from the 'data' attribute of your button then it won't make multiple requests when clicked since you have declared the variable globally!
Hope it helps.

How to make a form wait for ajax to finish before it submits?

So there is a form that i want to submit only when a condition is verified from the database using ajax. I am using preventDefault() method if the condition is true i.e. if a user is not a resident, a variable is set to true in ajax successs function and preventDefault() gets called, however, when doing this, the form always submits. It doesn't wait for the ajax to finish even when async is set to false.
Here's the code.
$('#button').click(function(e) {
if ($('#ca_resident').prop('checked') == true) {
amount=$('#user-amount').val().replace(/[,]/g,"");
project_name=$('#project_name').val();
var not_resident = false;
$.ajax({
url: '/main/verify_residence/',
type: 'POST',
aysnc: false,
data: {
value: amount,
name: project_name
},
success: function(data){
$("#verify_residence").html(data);
not_resident = true;
},
dataType: 'html'
});
}
if(not_resident){
e.preventDefault();
}
});
that won't work. Success will fire after:
if(not_resident){
e.preventDefault();
}
As it's asynchronous. You need to always cancel the button click then submit the form once success is hit:
$('#button').click(function(e) {
var $form = $(this).closest('form');
if ($('#ca_resident').prop('checked') == true) {
amount=$('#user-amount').val().replace(/[,]/g,"");
project_name=$('#project_name').val();
$.ajax({
url: '/main/verify_residence/',
type: 'POST',
aysnc: false,
data: {
value: amount,
name: project_name
},
success: function(data){
$("#verify_residence").html(data);
$form.submit();
},
dataType: 'html'
});
}
e.preventDefault();
});

jQuery don't post form after preventdefault

I have an form loaded by AJAX, and inside that form I have render the reCaptcha control.
When I post the form, first I validate, and that use my webservice to validate the captcha. If it all data is right I want to post the form.
But the last behavior don't append...
I read this posts:
Can't submit after preventDefault
How to reenable event.preventDefault?
Re-enabling Submit after prevent default
jQuery: call the action's form after calling preventDefault()
But none of the solutions work... :(
My code:
$('#myForm').submit(function (e) {
e.preventDefault();
var captchaInfo = {
challengeValue: Recaptcha.get_challenge(),
responseValue: Recaptcha.get_response(),
};
$.ajax({
type: 'POST',
url: '#Url.Action("ValidateCaptcha")',
data: JSON.stringify(captchaInfo),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
if (msg) {
$('#myForm').submit();
}
else {
helpers.setCaptcha("captcha");
}
},
error: function (req, status, error) {
alert("error: " + error);
helpers.setCaptcha("captcha");
},
});
});
How I resolve this?
Thanks in advance
When you call .submit() the same code will be called (ending up in possibly an infinite loop). Try restructuring and passing a value to the .submit() call, like this:
$('#myForm').submit(function (e, passThrough) { // <-- DECLARE HERE!!
if (passThrough) { // <-- CHECK HERE!!
e.preventDefault();
var captchaInfo = {
challengeValue: Recaptcha.get_challenge(),
responseValue: Recaptcha.get_response(),
};
$.ajax({
type: 'POST',
url: '#Url.Action("ValidateCaptcha")',
data: JSON.stringify(captchaInfo),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
success: function (msg) {
if (msg) {
$('#myForm').trigger("submit", [true]); // <-- PASS HERE!!
}
else {
helpers.setCaptcha("captcha");
}
},
error: function (req, status, error) {
alert("error: " + error);
helpers.setCaptcha("captcha");
},
});
}
});
The value passed (true), is available in the handler's parameters. So just check for that. If it's true, you know it was manually called and shouldn't validate the captcha, basically passing through the handler and allowing the default behavior.
Reference:
.trigger(): http://api.jquery.com/trigger/
Try removing the submit handler if it validates.
$('#myForm').off('submit');
Trigger the event on the form node itself.
$('#myForm')[0].submit()
this will cause it to bypass the jQuery bound event.

Categories

Resources