Execute ajax call right after all fields are filled - javascript

So I need to check all the fields first:
<script type="text/javascript">
<!--
$(document).ready(function(){
$("#loginform").submit(function(){
LIKE:
//CHECK INPUT
$('#loginform :input:not(:button)').each(function(n,element){
if ($(element).val()=='') {
$(".message").css('margin-top', '13px').html('<p>O campo '+element.id+' tem de ter um valor!</p>').fadeIn("slow").delay(2000).fadeOut(1000);
return false;
}
});
AND MAKE AJAX CALL AFTER ALL FIELDS ARE FILLED:
//AJAX CALL
$.post(...
BLÁ BLÁ
return false;
How can I submit values after check all fields?
Thank you as always.
UPDATE:
The solution "I found".
First validate in client side.
Second validate server side.
With the first measure several ajax call's are prevented before all fields are ok!
With the second "move" we prevent malicious intentions.
Thank you very much.
I been learning so much with you :)

Is this what your looking for?
var callAjax = true;
//CHECK INPUT
$('#loginform :input:not(:button)').each(function(n,element){
if ($(element).val()=='') {
//Code then set bool
callAjax = false;
}
});
if(callAjax){
$.ajax( {
url: "form action",
type: "POST",
data: $("#loginForm").serialize(),
....
}

If you mean whats the easiest way to get the form data into you ajax request?
use the .serialize() method on your form like:
$.ajax( {
url: "form action",
type: "POST",
data: $("#loginForm").serialize(),
....

// Add these to your onReady code
function checkFields() {
var filledIn = true;
$('#loginform :input:not(:button)').each(function(n,element){
if ($(element).val()=='') {
filledIn = false;
return false; // stop loop execution
}
});
return filledIn;
}
$('#loginform :input:not(:button)').change(function() {
if (checkFields()) {
$.ajax( {
url: "form action",
type: "POST",
data: $("#loginForm").serialize(),
....
});
}
})

Related

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

Have to click submit twice for AJAX request to fire on form submission

My Form HTML looks like this.
<form novalidate action="register.php" method="post" >
<label for="username">Username</label>
<input type="text" name="username" required placeholder="Your username" autofocus/>
<input type="submit" name="register" value="Register" cid="submit" />
</form>
And My jQuery looks like this
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
e.preventDefault();
});
The sad thing is that it logs hello to the console but it never submits the form with one click on the submit button. I need to press two times to submit button.
Can anyone tell me the problem and how can I fix it so that 1 click is sufficient for form submission.
NOTE: The data of form is send for validation not actually for submission . If data like email , username etc are valid i want the form to be submitted with one click.
Try separating the validation from the form submit.
Simply changing this line:
$("form").submit(function(e) {
to
$("input[name='register']").click(function(e) {
First of all I think it would be cleaner to use a success function instead of a .done() function. For example:
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
// Merge the check.php and register.php into one file so you don't have to 'send' the data twice.
url: "register.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON",
success: function() {
console.log("This form has been submitted via AJAX");
}
});
});
Notice that I removed the .unbind() function, as I suspect it might be the reason your code is acting up. It removes the event handlers from the form, regardless of their type (see: http://api.jquery.com/unbind/). Also, I put the e.preventDefault() at the start. I suggest you try this edited piece of code, and let us know if it does or does not work.
EDIT: Oh, and yeah, you don't need to submit it when you're sending the data via AJAX.
Try this one.
$("form").submit(function(e) {
var $form = $(this);
var serializedData = $form.serialize();
request = $.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datetype: "JSON"
});
request.done(function(response, textStatus, jqXHR) {
console.log("HELLO");
$('form').unbind();
$('form').submit();
});
});
$("form").submit(function(e) {
e.preventDefault();
var $form = $(this);
var serializedData = $form.serialize();
$.ajax({
url: "check.php",
type: "post",
data: { formData: serializedData },
datatype: "JSON",
success: function(data) {
return data;
}
});
});
So, to break it down.
Stop the form submission with the preventDefault().
Get the form data and submit it to your validator script.
The return value, I assume, is a boolean value. If it validated, it'll be true, or false.
Return the value which will continue the form submission or end it.
NB.: This is a horrible way to validate your forms. I'd be validating my forms on the server with the form submission, because javascript can be terribly easily monkeyed with. Everything from forcing a true response from the server to turning the submission event listener off.
Once I have the same issue
What I found is I have some bug in my url xxx.php
it may return error message like "Notice: Undefined variable: j in xxx.php on line ....."
It may let ajax run unexpected way.
Just for your info.
Instead of doing prevent default when clicking a submit button, you can create a normal button and fire a function when you click it, at the end of that function, submit the form using $('#form').submit();. No more confusing prevent default anymore.
You don't need to call submit() since you are posting your data via ajax.
EDIT You may need to adjust the contentType and/or other ajax params based on your needs. PHP example is very basic. Your form is most likely much more complex. Also, you will want to sanitize any php data - don't rely on just the $_POST
jQuery:
$("form").submit(function(e) {
$.ajax({
'type': 'post',
'contentType': 'application/json',
'url': 'post.php',
'dataType': 'json',
'data': { formData: $(this).serialize},
'timeout': 50000
).done(function(data) {
// Response from your validation script
if (data === true)
{
// SUCCESS!
}
else
{
// Something happened.
}
).fail(function(error) {
console.log(error);
});
e.preventDefault();
});
PHP
$is_valid = FALSE;
$name = $_POST['name'];
if ($name !== '')
{
$is_valid = TRUE;
}
else
{
return FALSE;
}
if ($is_valid)
{
// insert into db or email or whatver
return TRUE;
}

Given a form submit, how to only submit if the server first responses back with a valid flag?

I have a form, with a text input and a submit button.
On submit, I want to hit the server first to see if the input is valid, then based on the response either show an error message or if valid, continue with the form submit.
Here is what I have:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
if (data.valid) {
return true
} else {
// Show error message
return false;
e.preventDefault();
}
}
});
});
Problem is the form is always submitting, given the use case, what's the right way to implement? Thanks
Try like this:
$('#new_user').submit(function(e) {
var $form = $(this);
// we send an AJAX request to verify something
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
// if the server said OK we trigger the form submission
// note that this will no longer call the .submit handler
// and cause infinite recursion
$form[0].submit();
} else {
// Show error message
alert('oops an error');
}
}
});
// we always cancel the submission of the form
return false;
});
Since you're already submitting via AJAX why not just submit the data then if it's valid rather than transmit the data twice?
That said, the function that makes the Ajax call needs to be the one that returns false. Then the successvfunction should end with:
$('#new_user').submit()
The fact that AJAX is asynchronous is what's throwing you off.
Please forgive any typos, I'm doing this on my cell phone.
Submitting the same post to the server twice seems quite unnecessary. I'm guessing you just want to stay on the same page if the form doesn't (or can't) be submitted successfully. If I understand your intention correctly, just do a redirect from your success handler:
$('#new_user').submit(function(e) {
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $('#new_user').serialize(),
success: function(data){
location.href = "success.htm";
},
// if not valid, return an error status code from the server
error: function () {
// display error/validation messaging
}
});
return false;
});
Another approach
EDIT: seems redundant submitting same data twice, not sure if this is what is intended. If server gets valid data on first attempt no point in resending
var isValid=false;
$('#new_user').submit(function(e) {
var $form = $(this);
/* only do ajax when isValid is false*/
if ( !isValid){
$.ajax({
type: "POST",
dataType: 'json',
url: "/users/stuff",
data: $form.serialize(),
success: function(data){
if (data.valid) {
isValid=true;
/* submit again, will bypass ajax since flag is true*/
$form.submit();
} else {
// Show error message
alert('oops an error');
}
}
});
}
/* will return false until ajax changes this flag*/
return isValid;
});

jquery ajax call taking too long or something

I have a form that I want to ensure the paypal email address is valid before I submit. So i am making a jquery submit call like this
$('#new_user').submit(function(){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
return true;
}
}
});
but the problem is this call thats a second and the page already refreshes before the ajax is complete....if I put the return false at the end of the call I can see my json is correct but for some reason the way I have it now wont finish...any ideas on how to correct this
Just use preventDefault() immediately when the submit event is fired. Then wait for the response from paypal and then call submit() on the form.
$('#new_user').submit(function(e){
e.preventDefault();
var form = $(this); //save reference to form
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('#user_paypal_email').append('<span style="color:#E77776;">This is not a valid email address</span>');
return false;
}else{
form.unbind('submit'); //remove binding
form.submit(); //submit form
}
}
});
If you want to do something right away you would need to set async false in the request

jquery ajax json doesnt return true

i have large form in my website and using serialize() to process the form.
my problem is:
the result always return false after the form has been completed! i checked using firebug. if false, the result being shown. it was actually data.ok == true had been called, but it didnt show the message in the page? and it didnt redirect the page to the destination address?
jquery ajax:
$("#details").live("submit", function(e){
var form = $(this).serialize();
var data_string = form;
$.ajax({
type: "post",
url: "../_include/ajax.php?details",
cache: false,
data: data_string,
dataType: "json",
success: function(data) {
if(data.ok) {
("#pop").html(data.message).addClass("oke").fadeIn("slow");
setInterval(function() {
location.href = data.redirect
},2000)
} else {
$("#pop").html(data.message).addClass("warning").fadeIn("slow");
}
}
});
e.preventDefault();
})
in PHP:
if (isset($_GET['details'])) {
if (empty($name)) {
$data['ok'] = false;
$data['message'] = 'Please enter name!';
} ................ {
.............
} else {
$db->query("UPDATE query....");
$data['ok'] = true;
$data['message'] = 'Your details has been submitted!';
$data['redirect'] = 'index.php?p=details';
}
echo json_encode($data);
}
You appear to have a syntax error in your success function (if that's not a copy/paste error):
("#pop").html(data.message).addClass("oke").fadeIn("slow");
should be:
$("#pop").html(data.message).addClass("oke").fadeIn("slow");
you check for GET in your PHP (if (isset($_GET['details']))), but send POST (by specifying the type as post) in your AJAX.
Either check the $_POST array instead of the $_GET, or change the type to get.

Categories

Resources