My goal is:
When for is submitted:
a validation on form is made : OK
an ajax is called to see that username and password do match : OK
if they don't match, display an error: OK
if they match, then REALLY SUBMIT the form: NOT OK.
Infact the trouble is, I cannot submit the form since there is a jquery submit event on it!
function form1Submit() {
var username=$('#username').val();
var password=$('#password').val();
if (username.length<2) {
return false;
}
if (password.length<2) {
return false;
}
$.post("check.php", { username: username, password:password }, function(data) {
if (data=="ko") {
alert('bad password');
return false;
} else {
//to be done here !
}
});
return false;
}
function init() {
$('#form1').submit(function(){
return form1Submit();
})
}
$(document).ready(function(){
init();
})
You can call the native submit event, so do this:
$('#form1').submit(form1Submit);
Then in your post callback do this:
$.post("check.php", { username: username, password:password }, function(data) {
if (data=="ko") {
alert('bad password');
} else {
this.submit();
}
});
The this.submit() isn't calling he jQuery .submit() trigger function, but rather the native <form> .submit() function.
The return false is blocking the default form submit action. You have either to return true from the form1Submit() function to let the default form submit action do its job, or to add another $.post() inside the else which submits the data to the form asynchronously, if your intent was to do it using ajaxical powers.
The problem is that form1Submit always returns false.
function form1Submit(ev, ok) {
ev.stopPropagation();
ok = (typeof ok != 'undefined') ? ok : false;
if (ok)
return true;
var username=$('#username').val(),
password=$('#password').val(),
selfForm = this;
if (username.length < 2)
return false;
if (password.length < 2)
return false;
$.post("check.php", { username: username, password:password }, function(data) {
if (data=="ko") {
alert('bad password');
} else {
$(selfForm).trigger('submit', [true]); // again submit but with ok parameter
}
});
return false;
}
function init() {
$('#form1').bind('submit', form1Submit);
}
$(document).ready(function(){
init();
})
Related
I have the following Javascript code in my web page that SHOULD ensure data validation and then (if the form is valid) submit the data to an AJAX call:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.filter.call(forms, function (form) {
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
}
});
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>
The problem is, the validation works, but it doesn't. When the form fields are not valid, it hits this block:
if (form.checkValidity() == false) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
and the alert is displayed. The very next line should force the function to exit, stopping execution of any remaining code, but for some reason it doesn't. Instead, the remainder of the code executes as if the form is valid, and the alert for the AJAX failure pops up.
Why does the 'return false' not actually force the function to exit, and what am I missing here?
return false is a statement of the anonymous function function (form) {... which is called for each form element. The anonymous function function (event) {... doesn't have a return statement. The filter function in Array.prototype.filter.call(forms, has to return either true or false for each element to work as expected, not false or undefined. You could use e.g. Array.prototype.every and/or Array.prototype.map instead of Array.prototype.filter:
<script>
$(document).ready(function () {
$("#frmInfo").submit(function (event) {
event.preventDefault();
var forms = document.getElementsByName('frmInfo');
var validation = Array.prototype.map.call(forms, function (form) {
if (!form.checkValidity()) {
form.classList.add('was-validated');
alert('Hit invalid user input');
return false;
}
else {
alert('Everything is valid');
form.classList.add('was-validated');
return true;
}
});
if (!validation.every(el => el)) return false;
var obj = Object.fromEntries(new FormData(event.target));
if (obj.Is_Body_HTML == 1)
obj.Is_Body_HTML = true;
else
obj.Is_Body_HTML = false;
if (obj.Is_Active == 1)
obj.Is_Active = true;
else
obj.Is_Active = false;
setDisabled();
var json = JSON.stringify(obj);
alert(json);
var request = $.ajax({
url: "../handlers/test.ashx",
method: "POST",
data: json,
dataType: "json"
});
request.done(function (msg) {
if (msg.Success == false) {
$('#infoErr').html('Should not have reached this!');
$('#toastInfoFail').toast('show');
}
else {
localStorage.setItem('cust_no', msg.ID);
document.location.href = 'getaddress.aspx';
}
});
request.fail(function (jqXHR, textStatus) {
$('#infoErr').html('Unable to contact server to process change request. Please try again later.');
$('#toastInfoFail').toast('show');
});
request.always(function (jqXHROrData, textStatus, jqXHROrErrorThrown) {
setEnabled();
});
});
$('#BestTelephone').inputmask("999-999-9999");
$('#FirstName').focus();
});
function setDisabled() {
$('#btnNext').prop('disabled', true);
}
function setEnabled() {
$('#btnNext').prop('disabled', false);
}
</script>
$.get in the code below returns a boolean value in JSON format named data. But whether the value of data is false or true preventDefault() prevents the submission of the form anyway.
$(document).ready(function() {
$("#username").blur(function() {
let username = document.getElementById("username").value;
$.get("/check", {
username_value: username
}, function(data) {
alert(data);
$("#submit").click(function(e) {
if (data) {
e.preventDefault();
} else if (!data) {
e.submit();
}
});
});
});
});
And this is the /check part
#app.route("/check", methods=["GET"])
def check():
"""Return true if username available, else false, in JSON format"""
get_username = request.args.get("username_value")
users = db.execute("SELECT username FROM users")
lenght = len(get_username)
i = 0
for user in users:
if get_username == users[i]["username"] or not lenght > 1:
return jsonify(True)
i += 1
return jsonify(False)
I am very new at coding business btw. Thanks for help.
Try change to capture the event from form ID instead of button this way:
$("#form").submit(function (e) {
if (!data) {
e.preventDefault();
} else {
e.submit();
}
});
e.submit() must be used in event from a submited form.
Make sure data is boolean type. and don't forget change the selector to your form ID.
I solve the problem by replacing the $.get with $.ajax. I guess the problem was about the fact that $.get only works async. So I used $.ajax's async paramater at false. Then it worked just as I want.
Last version of the code:
$(document).ready(function() {
$('#form').submit(function(e){
let username = document.getElementById("username").value;
let password = document.getElementById("password").value;
let confirmation = document.getElementById("confirmation").value;
var boolean_data;
$.ajax({url: "/check?username=" + username, type: 'get', async: false, success: function(data){boolean_data=data;}});
if(!boolean_data) {
alert("\"" + username + "\"" + " username is already taken.");
e.preventDefault();
}
else if(!password || !confirmation) {
alert("Pls povide a password and confrim it");
e.preventDefault();
}
else if(password != confirmation) {
alert("Passwords don't match");
e.preventDefault();
}
});
});
Thanks to everyone who commented and answered my question.
I'm trying to submit form using j-query, before submitting it should do some validation and in that I've validation for capcha using ajax. Everything works fine without ajax validation.
<form id="RegistrationForm" name="RegistrationForm" method="post" action="save.php" >
jquery code
$('#RegistrationForm').submit(function(){
//some validation goes here
if($('#captcha').val() != '')
{
var captcha = $('#captcha').val();
$.ajax({
url:'validate.php',
type:'POST',
data:{captcha:captcha},
success: function(data){
if(data == 'false')
{
alert('Wrong Captcha is typed!');
return false;
}
else
{
alert('enter');
document.getElementById("RegistrationForm").submit();
return true;
}
}
});
}
});`
while submitting form it shows alert "enter" but form not getting submitted.
Thanks in advance.
You probably need to change your variable to a JSON seening how you are retreiving from a php. if thats not the solution try
if (data){
}else{
}
FYI this is not jquery validation. Jquery validation is a library set up in order to make sure the proper fields are set up correctly before submitting. What you have done is tested if the captcha is correct after submitting.
try something like this
$(function(){
$('#RegistrationForm').submit(function(){
if($('#captcha').val() != ''){
var captcha = $('#captcha').val();
$.ajax({
url:'validate.php',
type:'POST',
async:false,
data:{captcha:captcha},
success: function(response){
if(response == 'false')
{
alert('Wrong Captcha is typed!');
return false;
}
else
{
alert('enter');
return true;
}
}
});
}
});`
})
Try making ajax synchronous
$.ajax({
url:'validate.php',
type:'POST',
async: false,
data:{captcha:captcha},
success: function(data){
if(data == 'false')
{
alert('Wrong Captcha is typed!');
return false;
}
else
{
alert('enter');
document.getElementById("RegistrationForm").submit();
return true;
}
}
});
I think the problem is when the ajax request returns other value than false , every time you are again calling from submit , i think every time it calls to submit function , but could not submit successfully . because it calls submit function recursively.
try
$('#RegistrationForm').submit(function(){
//some validation goes here
if($('#captcha').val() != '')
{
var captcha = $('#captcha').val();
$.ajax({
url:'validate.php',
type:'POST',
data:{captcha:captcha},
success: function(data){
if(data == 'false')
{
alert('Wrong Captcha is typed!');
return false;
}
else
{
alert('enter');
}
}
});
}
});
I have a form that submits shopping cart data to a payment gateway (WorldPay) payment processing page. I need to perform a couple of extra logic the moment the custom decides to proceed to the payment but before the form submission itself. Basically, I simply want to generate a unique reference to the order at the very last moment.
Here is the jQuery code for the submit event:
$(function(){
$('#checkout-form').submit(function(e){
var $form = $(this);
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
e.preventDefault();
$.ajax({
url: baseUrl + '/shop/ajax/retrieve-shopping-cart-reference/',
data: {}, type: 'post', dataType: 'json',
success: function(json){
if(json.error == 0){
$('#cartId').val(json.data.cart_reference_number);
$form.submit();
}else{
alert(json.message);
}
}
});
}else{
console.log('Submitting form...'); //Does not submit!
}
});
});
The problem is that during the second submit triggered within the success: clause, the form isn't submitted still. I am assuming event.preventDefault() persists beyond the current condition.
How can I get around this?
For performe the any operation before form submit i used the following menthod hope it wil help
$('#checkout-form').live("submit",function(event){
//handle Ajax request use variable response
var err =false;
var $form = $(this);
//alert($form);
var values = {};
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
//here you get all the value access by its name [eg values.src_lname]
var $cartIdField = $('#cartId');
console.log($cartIdField.val());
if($cartIdField.val() == ''){
$.ajax({
// your code and condition if condition satisfy the return true
// else return false
// it submit your form
/*if(condition true)
{
var err =true;
}
else
{
var err = false;
}*/
})
}
else
{
return true;
}
if(err)
{
return false
}
else
{
return true;
}
})
e.preventDefault() remove default form submit attribute which can not be reverted if applied once.
Use below code instead to prevent a form before submitting. This can be reverted.
$('#formId').attr('onsubmit', 'return false;');
And below code to restore submit attribute.
$('#formId').attr('onsubmit', 'return true;');
Only call e.preventDefault() when you really need to:
if(not_finished_yet) {
e.preventDefault();
}
<script LANGUAGE="JavaScript">
function confirmSubmit() {
jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
if(r) {
return true;
} else {
return false;
}
});
}
</script>
<form name='cancel_form'id='cancel_form' method='POST' action="">
<center>
<input type='submit' name='confirm_appointment' value='Cancel Appointment' onclick='return confirmSubmit();'>
</center>
</form>
<script type='text/javascript'>
var ajax_load = "<img class='loading' src='img/load.gif' alt='loading...' />";
var saveUrl = "<?php echo $this->url(array('controller' => 'appointment', 'action' =>'cancelsave'));?>";
$('#cancel_form').ajaxForm({ success: saveCallbk , url : saveUrl });
function saveCallbk(responseText) {
jAlert(responseText,'Alert Dialog');
if(responseText.indexOf("ERROR")<0) {
$(location).attr('href',redirectUrl);
}
}
</script>
When I submit the form I call this function and use jConfirm from jQuery. I print r. It's printing properly (e.g. true and false), but return false or return true has no effect -- it just shows the pop up and submits the form, and does not wait for confirmation. How to solve this?
The ajaxForm plugin takes care of the submission by itself and it needs a submit button. If I use:
function confirmSubmit() {
var agree=confirm("Is the Appointment Cancelled?");
if (agree) {
return true;
} else {
return false;
}
}
like default javascript it works well
Use type="button" instead of type="submit" and attach this on the click event of your form button.
$('#button').click(function () {
jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) {
if (r) {
$('#form').submit();
}
});
});
What Ivo said.
Your function confirmSubmit should return true or false.
Edit -
I am not familiar with jConfirm, but you may need to return the results from jConfirm, like this.
<script>
function confirmSubmit()
{
return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog',
function(r) {
if(r){return true;} else {return false;}
});
}
</script>
if this is the case, you could do away with confirmSubmit() altogether and just say:
$('#form').submit(function() {
return jConfirm('Is the Appointment Confirmed?', 'Confirmation Dialog', function(r) { return r; } );
});
Hope this helps...
Dang that Ivo is GOOD :-) Personally, i do what Ivo has demonstrated. Create an input of type="button", then delegate a click function.
This is how I cancel submit events using JavaScript and jQuery:
First I have a utility function called cancelEvent: (Which I picked up from this blog entry.)
function cancelEvent(e)
{
e = e ? e : window.event;
if(e.stopPropagation)
e.stopPropagation();
if(e.preventDefault)
e.preventDefault();
e.cancelBubble = true;
e.cancel = true;
e.returnValue = false;
return false;
}
Then I'll have the main JavaScript file that will contain code something like this:
function validateForm(e)
{
var validated = true;
/*
Validation code goes here.
If validation fails set validated to false
*/
//If validation fails then at the end I'll want to cancel the submit event
if(validated)
{
return true;
}
return cancelEvent(e);
}
jQuery(document).ready(function()
{
jQuery("#theForm").submit(validateForm);
}