Submit form after event.preventDefault? - javascript

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
});
});
}
});

Related

AJAX JQuery PHP mail sending form

I am working on a site which having 2 contact forms, and I use ajax jquery to send mail via php.
When I use single form and jQuery, it works fine.
And when I paste the jQuery code and modify as per form 2 variables, it works, but then first jQuery code is sending blank values.
Over all at a time, only 1 form is working for my HTML forms on different page.
I appreciate your help in advance.
Jquery code
var form=$('#contactform_forms');
var formMessages=$('#message');
$(form).submit(function(e){
$('#submit_btns')
.after('<img src="images/AjaxLoader.gif" class="loader" />')
.attr('disabled','disabled');
e.preventDefault();
var formData=$(form).serialize();
$.ajax({
type:'POST',
url:'contact.php',
data:formData
})
.done(function(response){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text('Thanks! Message has been sent.');
$(formMessages).fadeOut(10000);
$('#contactform_forms img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit_btns').removeAttr('disabled');
$('#contact_name').val('');
$('#contact_email').val('');
$('#contact_phone').val('');
$('#contact_message').val('');
}).fail(function(data){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if(data.responseText!==''){
$(formMessages).text(data.responseText);
}else{
$(formMessages).text('Oops! An error occured.');
}
});
});
jQuery code for form 2 with the same js file:
var form=$('#wholesalers_forms');
var formMessages=$('#message');
$(form).submit(function(e){
$('#submit_btns1')
.after('<img src="images/AjaxLoader.gif" class="loader" />')
.attr('disabled','disabled');
e.preventDefault();
var formData=$(form).serialize();
$.ajax({
type:'POST',
url:'wholesalers.php',
data:formData
})
.done(function(response){
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
$(formMessages).text('Thanks! Message has been sent.');
$(formMessages).fadeOut(10000);
$('#wholesalers_forms img.loader').fadeOut('slow',function(){$(this).remove()});
$('#submit_btns1').removeAttr('disabled');
$('#hs_name').val('');
$('#hs_email').val('');
$('#hs_company').val('');
$('#hs_vat').val('');
$('#hs_address').val('');
$('#hs_postcode').val('');
$('#hs_city').val('');
$('#hs_phone').val('');
$('#hs_message').val('');
}).fail(function(data){
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
if(data.responseText!==''){
$(formMessages).text(data.responseText);
}else{
$(formMessages).text('Oops! An error occured.');
}
});
});
When I use both as the above order: 1st one send empty value and second form working perfectly, if i remove 2nd jQuery then first code working fine, but second do not have code to send.
There are a few issues here. First I can see you've got duplicate element IDs on the page which will produce undefined results. Second, you shouldn't be copying and pasting code but iterating through (or making generic) your code, depending on the usage. This keeps your code DRY. Further reading here: https://en.wikipedia.org/wiki/Don%27t_repeat_yourself.
If you are still having trouble, add a jsFiddle with the specific parts of the code you are having trouble with.
I'd do something like this:
function getFormData(form_id) {
var form_data = {};
$.each($("#" + form_id).serializeArray(), function(i, obj) {
if (form_data[obj.name] == undefined) {
form_data[obj.name] = obj.value;
} else if (typeof form_data[obj.name] == Array) {
form_data[obj.name].push(obj.value);
} else {
form_data[obj.name] = [form_data[obj.name], obj.value];
}
});
return form_data;
}
function validate(form_id) {
var error = false;
//run some validation, which alters display and sets error to true on failure.
return error;
}
$(document).on("submit", "form", function(event) {
var form_id = $(this).attr("id");
if (validate(form_id)) { //If error is found.
event.preventDefault();
} else { //Else the form is good.
var form_data = getFormData(form_id),
url = (form_id == "contactform_forms") ? "contact.php" : "wholsalers.php";
$.ajax({
type: "post",
url: url,
data: form_data,
success: function(data) {
//Display a confirmation message.
}
})
}
});

jquery ajax onsubmit form error

I hava a form that is given below
<form name="frm_dcg" id="frm_dcg" method="post" enctype="multipart/form-data" action="" onsubmit="return validate_form();" >
<div class="login-form">
<div class="sign-in-htm">
-----------other codes-------
and the jquery function
function validate_form(){
var run_name = $("#run_name").val();
$.ajax({
url: "check_folder.php",
type: "POST",
data: "run_name="+run_name,
success: function (response) {
if(response=="OK"){
con = confirm("File already exists.. Do you want to replace existing file?");
if(con==true){
return true;
}else{
return false;
}
} else{
return true;
}
return false;
}
});
}
The ajax is working fine, but the problem is form is submitting in any conditions. even if it is returning false. Please go through my code and let me know if there is any logical mistakes.
Ajax is an asynchronous function, meaning the return false you are calling happens way after the form is submitted.
Instead you have to add the return false at the end of the validate_form() function.
function validate_form(){
var run_name = $("#run_name").val();
...
return false; // <-- before the ending curly brace
}
Note that the form should always return false. You can validate run_name use that to decide if you should do the ajax request or not.
function validate_form(){
var run_name = $("#run_name").val();
if (run_name.length > 5) { // just an example
// do ajax request
} else {
// show invalid message
}
return false; // always false so the form doesn't submit.
}
You're returning the true/false result within the success closure. This won't get passed up to validate_form(). You also have a logic bug in the success handler that always returns true even if the response wasn't 'OK'.
You'll need to do something like:
function validate_form(){
var form_success = false; // Always fail by default
var run_name = $("#run_name").val();
$.ajax({
url: "check_folder.php",
type: "POST",
data: "run_name="+run_name,
success: function (response) {
if (response == "OK"){
form_success = confirm("File already exists.. Do you want to replace existing file?");
}
form_success = false;
}
});
return form_success;
}

jQuery AJAX response always returns blank message

Hi I'am trying to make HTML form, and need to validate it before executing the form action. But the AJAX respond always returns a blank message?
$(function(){
$("#ajax-payment-form input[type='submit']").click(function(e) {
// Prevent form submission
e.preventDefault();
// Serialize data, make AJAX call
var str = $(this).serialize();
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this
}).done(function(msg) {
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
} else {
console.log(msg);
}
}).fail(function() {
// Catch ajax errors here
console.log('AJAX error');
});
});
});
PHP:
$post = (!empty($_POST)) ? true : false;
if ($post) {
$orderid = stripslashes($_POST['orderid']);
$amount = stripslashes($_POST['amount']);
$betingelser = stripslashes($_POST['betingelser']);
$error = ''; // Check ordreid
if (!$orderid) {
$error. = 'Venligst indtast dit ordreid.<br />';
} // Check amount
if (!$amount) {
$error. = 'Venligst indtast et beløb.<br />';
}
if (!$error) {
echo 'OK';
} else {
echo '<div class="notification_error">'.$error.
'</div>';
}
}
Can anyone tell me what wrong?
You're in the click handler of a submit button. You're calling $(this).serialize(), where this is that submit button. Calling serialize on the submit button is going to return an empty string.
So, you're not passing any data to the server. The first thing you do server-side is check empty($_POST), which it will be, so if ($post) is false, and none of your server-side code is eve executed.
You need to serialize the form, not the submit button.
A simple solution would be to serialize the form itself....
str = $('"#ajax-payment-form').serialize()
but really, the larger problem is that you're binding to the click of the submit button, instead of to the submit event on the form itself.
Instead of this rather convoluted way of handling form submits...
$("#ajax-payment-form input[type='submit']").click(function(e) {
Just do this:
$("#ajax-payment-form").submit(function (e) {
try this in jquery:
$.ajax({
type: "POST",
url: templateDir+"/payment_form/payment_process.php",
data: str,
context: this,
success: function(msg){
if(msg == 'OK') {
console.log('Validation passed, will submit form');
$(this).closest('form').submit();
}
else {
console.log(msg);
}
}
error: function(msg){
// if call fails or any error occurs
}
});

Prevent form submission in jQuery by ID

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.

simple form validation with jquery serialize() function

$(document).ready(function(){
$('#send').click(function() {
var names = $('#appontment_form').serialize();
//this is how my names variable look like
//doctor=Dr.Fathmath+Shahuda&date=2013-02-27&time=1900+-+1700&phone=
var doc = $(names).filter('doctor');
if(doc !='')
{
$.ajax({
type: "post",
url: "../../includes/jqueryRequireFiles/appointmentSave.php",
data:names,
success: function(data)
{
$('#confir').text('Your Appointment Received..');
}
});
return false;
}
});
});
I have a appontment form. when i click send link it will grab all the values in the textboxs and put it in the names variable through serialize() function. i want to filter the names variable and find out if any of the field is left not filled.. if only if then i will make the ajax part.. but its not working...any help
When you use $.serialize() the variable content looks like ?key=value1&key=value2. If you want to validate the form, just do it without serialize like
var found_errors = false;
if($('#formfield1').val().trim() == "") {
//Handle errors if field is empty
found_errors = true;
}
And if no errors are found, serialize the form and send it.
Consider using jQuery validation plugin.
http://docs.jquery.com/Plugins/Validation

Categories

Resources