jquery ajax call taking too long or something - javascript

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

Related

Prevent submit on a jQuery form

I'm setting up a password control on a login form with jQuery and ajax.
So far, this is the script
$(document).ready(function() {
$("#login-form").submit(function(e) {
var csrftoken = getCookie('csrftoken');
var password = $('#login-password').val();
var email = $('#login-email').val();
$.ajax({
url: "/password_check/",
type: "POST",
dataType: "json",
data : {
csrfmiddlewaretoken: csrftoken,
password: password,
email: email
},
success: function(result) {
document.getElementById("login-error").innerHTML = result.response;
event.preventDefault();
}
});
return false;
});
});
With this, the error gets caught when firing the submit button, but if the password is correct the submit doesn't work (even though the error doesn't show up anymore).
What am I missing?
You have an asynchronous ajax call, so by the time your success function fires, the form submit event has passed so you need to submit the form again but use the DOM method, which will bypass the jQuery event handler and allow the form to submit.
success: function(result) {
if(result == "correct"){
document.getElementById("login-form").submit();
} else {
document.getElementById("login-error").innerHTML = result.response;
}
}
As you didnt say what response indicates a correct password, I have used result == "correct", so change that accordingly.
You have to return false only if u dont want to submit the form.
If password is correct you need to return true in your case.

How to disable form (user cannot checked, fill text , select dropdown etc.) in this form when process requests post ajax?

How to disable form (user cannot checked, fill text , select drop down etc.) in this form when process requests post ajax ?
i want to disable form id="f1" when process send post ajax , How can i do that ?
<script>
function send_requests_data(){
$('#demoajax').hide();
$('#loading').show();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#f1').serialize(),
success: function(data){
$("#loading").fadeOut("slow");
$('#demoajax').show();
$('#demoajax').html(data);
}
});
return false;
}
// on load page call function code //
$(document).ready(send_requests_data());
</script>
A possible answer may be found here:
disable all form elements inside div
TL;DR
try adding this:
$("#parent-selector :input").attr("disabled", true);
to the ajax call where parent-selector is either the div or form id.
try this i hope it helps :
function send_requests_data(){
$('#id1 input,select').attr('disabled','disbaled');
$('#demoajax').hide();
$('#loading').show();
$.ajax({
url: 'test.php',
type: 'POST',
data: $('#f1').serialize(),
success: function(data){
$("#loading").fadeOut("slow");
$('#demoajax').show();
$('#demoajax').html(data);
$('#id1 input,select').removeAttr('disabled');
}
});
return false;
}
$.each($('input, select ,textarea', '#f1'),function(){
$(this).prop('disabled', true);
});
You can call the below function before calling your ajax function. It will disable all your form controls
function disable() {
var limit = document.forms[0].elements.length;
for (i=0;i<limit;i++) {
document.forms[0].elements[i].disabled = true;
}
}

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

how come this asyncronous call is not stopping on return false [duplicate]

This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
jquery ajax call taking too long or something
for some reason this ajax call
$('#new_user').submit(function(e){
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
async: false,
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false){
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('.error_messages').remove();
$('<span class="error_messages" style="color:#E77776;margin-left: 10px;">This is not a valid paypal email address</span>').insertAfter('#user_paypal_email');
return false;
}
}
});
});
is still submitting the form even after prints out my error and my return false....why is that
$.ajax is a function call which defines an AJAX callback then and the .submit function ends. Separately (asynchronously) the AJAX call is made and your success function then returns false to basically nothing since .submit has already finished.
What you really want to do is halt the form submission process, waiting for the AJAX call to finish, then decide if it should continue. This can be achieved by completely stopping the form submission the first time, then manually resubmitting it once you've got the AJAX callback. Of course the trick is how do you know it's valid? You could throw a value on the submit element.
Example:
$('#new_user').submit(function(e){
var submitElem = $(this);
// Check for previous success
if (submitElem.data('valid') !== true) {
$.ajax({
type: 'post',
url: "/validate_paypal",
dataType: 'json',
async: false,
data: {email : $('#user_paypal_email').val()},
success: function( data ) {
if (data.response["valid"] == false) {
$('#user_paypal_email').closest('.field').addClass('fieldWithErrors');
$('.error_messages').remove();
$('<span class="error_messages" style="color:#E77776;margin-left: 10px;">This is not a valid paypal email address</span>').insertAfter('#user_paypal_email');
return false;
} else {
// If successful, record validity and submit (allowing to continue)
submitElem
.data('valid', true)
.submit();
}
}
});
return false;
} else {
// Fall through
return true;
}
});

Categories

Resources