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.
Related
Here, I have a function which needs to be called before any AJAX call present in the .NET project.
Currently, I have to call checkConnection on every button click which is going to invoke AJAX method, if net connection is there, proceeds to actual AJAX call!
Anyhow, I want to avoid this way and the checkConnection function should be called automatically before any AJAX call on the form.
In short, I want to make function behave like an event which will be triggered before any AJAX call
Adding sample, which makes AJAX call on button click; Of course, after checking internet availability...
//check internet availability
function checkConnection() {
//stuff here to check internet then, set return value in the variable
return Retval;
}
//Ajax call
function SaveData() {
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
And below is current way to call function:
<form onsubmit="return Save();">
<input type="text" id="txtYears" /><br />
<input type="submit" id="btnSave" onclick="return checkConnection();" value="Save" />
<script>
function Save() {
if (confirm('Are you sure?')) {
SaveData();
}
else {
return false;
}
}
</script>
</form>
You cannot implicitly call a function without actually writing a call even once(!) in JavaScript.
So, better to call it in actual AJAX and for that you can use beforeSend property of ajaxRequest like following, hence there will be no need to call checkConnection() seperately:
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
beforeSend: function() {
if(!checkConnection())
return false;
},
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
It reduces the call that you have made onsubmit() of form tag!
UPDATE:
to register a global function before every AJAX request use:
$(document).ajaxSend(function() {
if(!checkConnection())
return false;
});
The best way is to use a publish-subsribe pattern to add any extra functions to be called on pre-determined times (either before or after ajax for example).
jQuery already supports custom publish-subsrcibe
For this specific example just do this:
//Ajax call
function SaveData(element) {
var doAjax = true;
var YearData = {
"holiday_date": D.getElementById('txtYears').value
};
if (element === myForm)
{
doAjax = checkConnection();
}
if ( doAjax )
{
$.ajax({
type: "POST",
url: 'Service1.svc/SaveYears',
data: JSON.stringify(YearData),
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data, status, jqXHR) {
//fill page data from DB
},
error: function (xhr) {
alert(xhr.responseText);
}
});
}
else
{
// display a message
}
}
Hope i understand correctly what you mean.
UPDATE:
in the if you can do an additional check if the function is called from the form or a field (for example add an argument SaveData(element))
If you use the saveData in html, do this: "saveData(this)", maybe you should post your html as well
You can use:
$(document)
.ajaxStart(function () {
alert("ajax start");
})
.ajaxComplete(function () {
alert("ajax complete");
})
That's it!!
use
beforeSend: function () {
},
ajax method
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/
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.
I have a login form with a username and password.
I make a post to a web service with the user and pass as parameters and I get back an ID for that user.
What I am trying to achieve is that on form submit, the ajax call is made which in turn populates the ID field (which I need) and then submits the form using $('#form1').post();.
To prevent default behavior, I have a return false; at the beginning of the .submit() event.
$('#form1').submit(function() {
$('#sajax-loader').show();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{user:"' + $("#user").val() + '",pass:"' + $("#pass").val() + '"}',
url: "URL.asmx/validate",
dataType: "json",
success: function (data) {
$('#id').val(data.d);
$('#sajax-loader').hide();
$('#form1').post();
$('#login-notification').show();
},
error: function (err) {
$('#login-notification').html("An Error Occured " + err);
}
});
return false;
});
Obviously this is the wrong approach since I am not getting any response when submitting.
Can anybody guide me in the right direction? Give some advice on how to tweak this submit function I have here, or maybe an entirely different more practical approach?
Beginning return false will stop the execution of submit() function at that point from where you return and rest of the code is not executing. So, place your return false at the end.
In other way, using .preventDefault() will stop default form submission behavior.
$('#form1').submit(function(e) {
// instead of return false
// use e.preventDefault()
e.preventDefault();
$('#sajax-loader').show();
$.ajax({
type: "POST",
contentType: "application/json; charset=utf-8",
data: '{user:"' + $("#user").val() + '",pass:"' + $("#pass").val() + '"}',
url: "URL.asmx/validate",
dataType: "json",
success: function (data) {
$('#id').val(data.d);
$('#sajax-loader').hide();
$('#form1').post();
$('#login-notification').show();
},
error: function (err) {
$('#login-notification').html("An Error Occured " + err);
}
});
});
And one thing
Instead of
data: '{user:"' + $("#user").val() + '",pass:"' + $("#pass").val() + '"}',
you can use:
data: {user: $("#user").val() ,pass: $("#pass").val() },
I want to validate a form with the jQuery form validation plugin but I was not able to send a custom Ajax request with the validation handler:
$('#headForm').validate(
{
//submitHandler: submit,
errorClass: "invalid",
rules: {
title: {maxlength: 50}
},
messages: {
title: {maxlength: 'Max 50 chars'}
}
});
My orginal submit handler looked like this:
$('#headForm').submit(function(event)
{
event.preventDefault();
$.ajax(
{
type: "PUT",
url: "/target",
data: $('#headForm').serialize(),
dataType: "json",
success: function()
{
alert("ok");
}
});
});
I tried to move it to a usual function and register it as a submitHandler in the validation block, but it didn't work.
function submit() { // impossible to pass the event!
$.ajax( ...
}
How can I combine jQuery validation with a custom Ajax request?
Possible form validation bug:
I've removed the validation code to see whether the submission works without it. And it did not unless I removed the link to jQuery form validation library! So it seems like validation is breaking jQuery core. Have I already said that I love dynamic typing ... ;-)
Did you define a parameter in the submit() function?
(I'm guessing that you didn't, and that could be why it didn't work)
I think you just need to specify the 'form' parameter, and then call serialize() on that parameter, as follows:
submitHandler: function(form) {
$.ajax({
type: "PUT",
url: "/target",
data: form.serialize(),
dataType: "json",
success: function()
{
alert('ok');
}
});
}
See the docs: http://docs.jquery.com/Plugins/Validation/validate#options