Prevent form submission in jQuery by ID - javascript

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.

Related

Submit form after event.preventDefault?

I know this question has been asked a million times but i just cant seem to make it work. Can someone let me know what I'm doing wrong.
Here's my code:
$('#frm').submit(function(event) {
event.preventDefault();
var formData = $(this).serialize();
var email = $('input#email').val();
if (email == '') {
alert('Please enter your email address');
$('input#email').focus();
return false;
} else {
$.post('http://www.domain.com/', formData, function() {
$('#frm').submit();
});
}
});
You can submit the FORM using DOM node submit method:
$.post('http://www.domain.com/', formData, function() {
this.submit(); // 'this' not '$(this)'
}.bind(this)); // 'bind' to set relevant context, or use jq $.proxy(handler, this) to support older browsers
This code does not make sense
$.post('http://www.domain.com/', formData, function() {
$(this).submit();
});
you are posting and then, when the request returns with success, you are trying to call submit on the form again?
by the way, this in that context refers to the jqXHR object of the Ajax call and not to the form. See $(this) inside of AJAX success not working
As most of the answers said, this is not a reference to the form. Then you will need to create a reference for it as follows (see that var). HOwever that is only needed if you want to use it later in the success callback:
$('#frm').submit(function(event) {
// Create a reference to your form
var that = this;
event.preventDefault();
var formData = $(this).serialize();
var email = $('input#email').val();
if (email == '') {
alert('Please enter your email address');
$('input#email').focus();
return false;
} else {
$.post('http://www.domain.com/', formData, function() {
// On success response do your stuff here and
// submit to your 'own domain'
// In case you don't have the action attr, give a value to this var.
var url = $(that).attr('action');
$.post(url, formData, function() {
// On success response do your stuff here
});
});
}
});

How to display comment form submit without refresh the page using AJAX?

Comment Form is submitting and also data getting saved to the database. But not displaying on the browser without refreshing the page.
here is the code:
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
EDIT:
All i can understand is i haven't published the data with ajax??
Is this what i need to do??
$("#post_reply").click(function (event) {
$("#data_status").html("");
$('#ajax_loading').show();
event.preventDefault();
if (document.getElementById('_comment').value.trim() == "") {
return false;
}
$.post('../services/leave_comment.php', $("#open_status").serialize(), function (data) {
$('#ajax_loading').hide();
if (data.split("::")[1] == true) {
$("#data_status").html("Commented Successfully..");
$("#data_status").fadeOut(3000);
document.getElementById('_comment').value = '';
$('#_comment').html("");
$.ajax({
type: 'POST',
url : 'http://localhost/tech1/services/get_more_comments.php',
data: 'last_id='+last_id,
success: function(data){
$('.view_container').append(data);
},
complete: function(){
console.log('DONE');
}
});
} else if (data.split("::")[1] == false) {
$("#data_status").html("Error occured in Comment Submission.. TryAgain..");
$("#data_status").fadeOut(3000);
}
});
});
All your code does is post the data to the server. There is nothing that fetches the new comments from the server or manually appends the posted comment. You can either use ajax again to refresh comments or more simply append a comment with the posted content.
I would say to search the web for jQuery's .load :
example:
function updateShouts(){
// Assuming we have #shoutbox
$('#shoutbox').load('latestShouts.php');
}
in this case shoutbox would be the containing div with your comments,
you would call this function on the success of your ajax post
latestshouts.php would only contain the content of that div.
kinda hard to explain, i hope it makes sense to you
link: http://api.jquery.com/load/

How do I submit a form using jQuery after AJAX validation?

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.

Performing ajax Checks Before Form Sumbit via Javascript

I have a simple form which is used to sign up a new user . I want to prevent users from submitting the same email id again . So before the form gets submitted , I want to do an Ajax check if the email id exists or not . If the email id exists , I alert the user . If it doesnt , I let the form be submitted .
$("#sign_in_form").submit(function(event){
event.preventDefault();
$.post("http://xyz.com/check_if_user_exists", {
email : $("#contact_person_email").val()
}).done(function(data) {
var res = parseInt(data);
if(res==1){
//Email Exists
alert("Email exists . Please use different email " );
return false; //----------------------------1)
}else{
//Email doesnt exist
return true; //--------------------------- 2)
}
});
//end of function
});
The problem with this code is due to async nature of Javascript , the function ends even before the result is returned from the ajax post statement . Hence the return false or return true statement at 1) and 2) have no effect . Whats the correct way to handle this ?
Submit form using js native event if check is valid:
$("#sign_in_form").submit(function (event) {
event.preventDefault();
$.post("http://xyz.com/check_if_user_exists", {
email: $("#contact_person_email").val()
}).done(function (data) {
var res = parseInt(data);
if (res == 1) {
//Email Exists
alert("Email exists . Please use different email ");
} else {
document.getElementById('sign_in_form').submit();
}
});
//end of function
});

$posts jquery submits my form

<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.

Categories

Resources