Matt Elhotiby
Matt Elhotiby

Reputation: 44066

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

Upvotes: 0

Views: 6734

Answers (2)

user342706
user342706

Reputation:

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

Upvotes: 1

Aaron
Aaron

Reputation: 148

If you want to do something right away you would need to set async false in the request

Upvotes: 0

Related Questions