<script type="text/javascript">
function claim()
{
var c = confirm('You sure?');
if(c)
{
var password=prompt("Please mention pw","");
if (password!=null && password!="")
{
$.post("/claim/<?php echo $refnr; ?>", { partner_pwd: password },
function(data) {
alert(data);
if(data == '1')
{
return true;
}else{
return false;
}
});
}else{
return false;
}
}else{
return false;
}
}
</script>
When testing I get to the Please mention pw, after i entered and press OK it submits my form, instead of making the $.post and only submit my form if data == '1' (return true)
claim() is called at my submit button;
<input type="submit" name="submit" onclick="return claim()"; value="Submit" />
I tried alert debugging and it was true like i thought it automatically submits when it reads the $.post(), I only wish it to submit (by returning true) if the data is 1.
Well, if you put a form in a website, it's goal is to submit the form.
http://api.jquery.com/submit/ (scroll down to the very last example starting with Example: If you'd like to prevent forms from being submitted unless a flag variable is set, try:)
As stated in the link above, you should change form's action instead of some page and do something like action="javascript:claim()". I think that should work.
The return true and return false inside of your $.post request do nothing but return out of that callback. It does not prevent the form from submitting. Instead, try preventing the submit completely and then triggering it if you want the submit to happen.
function claim() {
var c = confirm('You sure?');
if (!c) {
return false;
}
var password = prompt("Please mention pw", "");
if (password != null && password != "") {
$.post("/claim/<?php echo $refnr; ?>", {
partner_pwd: password
}, function(data) {
alert(data);
if (data == '1') {
$("#myform").submit();
}
});
}
return false;
}
Note how we always return false out of that function regardless of the validity. If it is valid, we trigger the form's submit event directly.
Your onclick method on the submit it's not working because the form will be submitted eitherway.
You should for example set a listener on the onsubmit(); event on the form
or another solution is on the put the onsubmit attribute with your javascript function in it and submit the form from your javascript with the $('#form').submit(); function.
Related
I am a little confused on how to take control of the submit event in a form, and I have tried to find a simple answer here.
I want to validate the form input before sending the form data to the form action scrip. I have tried to solve this by capturing the submit event, calling a validation script with Ajax, and if the validation succeeds I want the actual form procedure to be called. But I'm not sure how to proceed. Simply using location.replace("action.php") seems to fail (I guess that the form values aren't sent).
Here's the conceptual code:
$("form").on("submit", function(event) {
event.preventDefault();
data = {
the_input_val: $("#input_to_be_validated").val()
};
$.post("ajax_validate_input.php", data, function(data, status) {
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
// Here I want to send the form data. But the event.preventDefault() prevents it from happening
// What do I put here to call the form's 'action' script with form data?
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="action.php">
<input id="input_to_be_validated" name="my_input" type="text">
<button type="submit" name="submit">Submit</button>
</form>
Call the submit() method on an HTMLFormElement to manually submit the form without passing through the submit event again.
The form can be retrieved by reading out the target property of the event object.
Though, to make this work, lose the name="submit" value on your button, as this will cause an error trying to submit with the method.
const $form = $("form");
$form.on("submit", function(event) {
event.preventDefault();
const data = {
the_input_val: $("#input_to_be_validated").val()
};
$.post("ajax_validate_input.php", data, function(data, status) {
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
event.target.submit();
}
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<form action="action.php">
<input id="input_to_be_validated" name="my_input" type="text">
<button type="submit">Submit</button>
</form>
You can use the submit() method like this:
if (status == "success") {
if (data == "invalid") {
alert("Invalid input");
// Form data is not sent... as expected
} else {
event.submit();
}
}
I am trying to submit a form after validation and confirmation. But after the validation the form is not getting submitted. If I do not validate and confirm then the form is being submitted. What am I doing wrong here? Please tell me how to rectify it.
<div class="button secondary" id="contact_submit">
Create/Update <span class="icon-right icon-check"></span>
</div>
function validateFields() {
#some validation operations
if(validated){
if(operation == "Create"){
$("#contact-form")[0].setAttribute("action", "/contact/create_contact/");
$("#contact-form")[0].setAttribute("method", "POST");
}
else if(operation == "Update"){
$("#contact-form")[0].setAttribute("action", "/contact/" + object_id + "/update_contact/");
$("#contact-form")[0].setAttribute("method", "PATCH");
}
$('#contact-form').on('submit', function(e){
e.preventDefault();
$.ajax({
url: '/oms/getIsPrimaryContact/',
type: 'GET',
data: { object_id: object_id },
success: function(data) {
if ($('.element-contact#is_primary_contact').prop("checked") && !data.is_primary_contact) {
var c = confirm('Are you sure you want to change the primary contact?');
if (c) {
return true;
} else {
return false;
}
}
},
error: function() {} });
});
$('#contact-form').submit();
}
}
$(document).ready(function(){
$("#contact_submit").click(function(e) {
validateFields()
});
});
It just shows the confirmation box and if I click on ok or cancel then also the ajax call is being initiated. If the checkbox is not checked then also the form is not being submitted.
On clicking either button in the confirmation box the form should be submitted or not submitted and if the checkbox is not checked then the form should just be submitted.
But instead ajax call is happening on clicking any button.
I am using jQuery Ajax function to check the existence of user email in the database on jquery change function. in Ajax responsive there are two possibilities that either user email exists or not. If it exists it shows the error message. Now I wanted to prevent the form from submitting if the Ajax responsive is false
jQuery("#userEmail").change(function(){
//my code goes here
if(result == 'False'){
//prevent form here
}
else {
// else condition goes here
}
});
You can put a global variable like
emailValidated = false
And on
jQuery("#userEmail").change(function(){
//my code goes here
if(result == 'False'){
emailValidated = false;
}
else {
// else condition goes here
emailValidated = true;
}
});
After that on form submit check the value of the emailValidated variable.
$(form).submit(function(){
if(emailValidated) {
this.submit();
}
else {
return false;
}
})
Use e.preventDefault() to prevent form from submission.
jQuery("#userEmail").change(function(e){
if(result == 'False'){
e.preventDefault();
}
else {
}
});
Do something like this:
var result;
$.ajax({
url: url,
// Put all the other configuration here
success: function(data){
if(data == something) // replace something with the server response
result = true; // Means that the user cannot submit the form
},
});
$('#formID').submit(function(){
if(result){
alert('Email already exists.');
return false;
}
});
Steps are like :
get the email value passed by the user from input field in Jquery.
The POST that data to your PHP query file and get the response data on "success: function(data)" function of jquery.
Display that data data on the page..
Check below link for a reference.
http://www.sitepoint.com/jquery-ajax-validation-remote-rule/
You need use the submit event handler:
jQuery("#userEmail").closest("form").submit(function(event){
var $email = jQuery("#userEmail", this);
//the email field is not `this`, but `$email` now.
//your code goes here
if(result == 'False'){
event.preventDefault();
}
else {
// else condition goes here
}
});
You can still attach other behaviours to the change event if needed. The important thing is to do event.preventDefault() on the submit event.
My form has one input which needs to be validated before submitting. After a successful validation I try to submit the form, but it doesn't submit.
My code looks like this:
$(document).ready(function() {
$("#myForm").submit(function () {
checkInputData();
return false; // to prevent default submit
});
});
The validation function:
function checkInputData() {
var id = $($("#id")).val(); // value, which needs to be validated
$.get("check.php?id=" + id,
function(result){
if(result == 1) {
//if the result is 1, need to submit
$("#myForm").unbind(); // to prevent recursion?
$("#myForm").submit(); // doesnt work
} else {
// dont submit, give some visual feedback, etc...
}
});
}
What am i doing wrong? Thanks.
You need to return the result from your AJAX validation request. You can do this by setting this check to being async: false, this means the checkInputData() will wait for the result to come back, and you can return it, controlling the submission of the form.
In your code it's not waiting for the $.get action to happen, and it appears to skip over meaning your code will always appear to return true; from the checkInputData() call. You don't need to return false in submit, if used as below.
I have used the $.ajax call in place of $.get because it allows you to control the async property, but it essentially does the same thing. You can read more about it here.
function checkInputData() {
var value = $("#id").val(); // Value to be validated
var passedValidation = false;
$.ajax("check.php?id=" + value, {
async: false,
success: function(result){
// Do whatever check of the server data you need here.
if(result == "1") {
// Good result, allow the submission
passedValidation = true;
} else {
// Show an error message
}
}
});
return passedValidation;
}
$(document).ready(function() {
$("#myForm").on("submit", function () {
return checkInputData();
});
});
I assume you have a button such as below, within your form with id myForm:
<input type="submit" value="Submit Form" />
It's not getting submitted may be because you are not returning 1 on successful validation for result in below if condition
if(result == 1) {
In check.php your output should be 1, like echo '1'; if input is valid. And make sure there is not any other output before or after it.
AMember is correct your always returning false, there are a few solution. One solution is for you to bind your validation to a button element or any element that will not submit the form.
HTML
<form id="myForm">
.
input elements
.
<button class= "submit" type="button" onclick="submit">Submit</button>
</form>
Document Ready
$(function()
{
var $submit = $(".submit");
$submit.click(function ()
{
checkInputData();
});
});
Validation Callback Function
function checkInputData()
{
var id = $('#id').val(); // value, which needs to be validated
$.get("check.php?id=" + id, function(result)
{
if(result == 1)
{
var $myForm = $("#myForm");
//if the result is 1 submit.
$myForm.submit();
}
else
{
// dont submit, give some visual feedback, etc...
}
});
}
$(document).ready(function() {
$("#myForm").submit(function (e) {
checkInputData();
//return false; // to prevent default submit <-- THIS IS WRONG
e.preventDefault(); //Try this :)
});
});
Returning false will prevent it from submitting in all cases.
So I'm pretty new to Javascript and even newer to jQuery. Working on this project atm, I started with Javascript but a lot of the solution to my issues were a lot easier in jQuery.
so I have some javascript which basically prevents the user from pressing submit if all the forms have not passed validation.
So this is my field.
<td><input type="password" maxlength="16" name="passwd" id="passwd" onblur="validatePassword(this.value)" /></td>
<td><span id="pMess"></span></td>
This is my submit.
<td><input type="submit" value="Register" onclick="return validate(this.form)"/></td>
<td><a href='Index.php'>Login?</a></td>
As you can see when you press submit it goes to the validate function which is:
function validate(theForm) {
var valid = true;
if ( !validateEmail(theForm.emailrec.value) ) valid = false;
if ( !validatePassword(theForm.passwd.value) ) valid = false;
if ( !validatePostcode(theForm.postcode.value) ) valid = false;
if ( valid ) return true;
else return false;
}
And finally this is the field checker.
function validatePassword(passwordString) {
var valid = true;
if ( passwordString == "" ) {
feedback('pMess','Enter your password here');
valid = false;
} else if ( passwordString.length <= 5 ){
feedback('pMess','Password too short');
valid = false;
} else feedback('pMess','Acceptable');
if ( valid ) return true;
else return false;
}
My username field checker is slighty different as it's in jQuery
$(document).ready(function() {
$('#username').keyup(username_check);
});
function username_check() {
var username = $('#username').val();
if(username == "" || username.length < 6){
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function(response){
if(response == 1) {
$('#username').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
}
}
});
}
}
so what I'm trying to do is get username_check to return like my other field checkers. I'm just looking for help as to where I should put the returns and stuff. Whatever I try seems to break the code...
All I have so far
if ( !check_username(theForm.username.value) ) valid = false;
Any help at pointing me in the right direction would be much appreciated.
The problem is not jQuery. The problem is that you are using an asynchronous call to do some of your validation. jQuery.ajax is asynchronous, meaning that code will continue to execute while it fetches check.php. In other words, by the time the response comes back, username_check() will have already returned and submitted your form (or cancelled the submit).
For the non-AJAX part of your code (the length check), you can do a return just fine:
function username_check() {
var username = $('#username').val();
// NOTE: This is redundant, as "" has length 0
if(username == "" || username.length < 6){
$('#username').css('border', '3px #CCC solid');
$('#tick').hide();
$('#cross').fadeIn();
return false; // This will work here
} else {
// AJAX stuff
}
}
Unfortunately, the rest gets a bit more tricky. What you really want to do, is wait to sumbit your form until the username check is done, which means your submit needs to go in the callback function (i.e. the success part of your AJAX). If you only have one AJAX call, this is not too bad. If you have multiple AJAX calls, you need to either nest all of the calls (which makes the code take longer, is not very pretty, and will not easily proceed to other checks after one fails) or you need to use deferred objects (or something similar), which are not trivial (but very useful).
Assuming you have a single AJAX call for username:
First, add an ID to your submit button. This makes it easier to reference from jQuery:
<td><input id="mysubmit" type="submit" value="Register" onclick="return validate(this.form)"/></td>
<td><a href='Index.php'>Login?</a></td>
Secondly, do the username check after all of the other checks, and only submit if the other checks were valid:
function validate(theForm) {
var valid = true;
if ( !validateEmail(theForm.emailrec.value) ) valid = false;
if ( !validatePassword(theForm.passwd.value) ) valid = false;
if ( !validatePostcode(theForm.postcode.value) ) valid = false;
// The non-AJAX checks for username length:
var username = theForm.username.value;
if ( !validateUsername(username) ) valid = false;
jQuery.ajax({
type: "POST",
url: "check.php",
data: 'username=' + username,
cache: false,
success: function(response){
if(response == 1) {
$('#username').css('border', '3px #C33 solid');
$('#tick').hide();
$('#cross').fadeIn();
} else {
$('#username').css('border', '3px #090 solid');
$('#cross').hide();
$('#tick').fadeIn();
// If the other checks were OK, submit the form manually
if(valid) {
$("#mysubmit").submit();
}
}
}
});
// ALWAYS return false.
// We will submit the form manually if the checks are OK
// For now, prevent the submit
return false;
}
Make sense?
Notes:
You probably want to disable the submit button after it is clicked (and re-enable it on failure. Otherwise, if the AJAX takes a while, a user could potentially change the field values before its callback, allowing bad data to be submitted without checks.
The other solution to this is to do the checks onsubmit. Currently, your checks are not called if the user pressed the enter key. This is bad!
Not sure if I follow, you want the function to return true or false if validates, right?
Edit: my code was crap, thanks roasted for pointing that out.
So, as you are doing an ajax call you can't really get if it's valid (true or false) in the same function, you probably need to do something different....
A couple of ideas;
-Use your DOM (add an "invalid" class or something like that to the form field and then check for that value.
-Use a global variable "valid_user" saving the result of the validation... ( i know global variables suck and it's a bad practice, but hey, if you have a deadline...)
then, when you are validating the hole form, check for this things instead of calling username_check again.
Hope this helps!