rocket_boomerang_19
rocket_boomerang_19

Reputation: 563

Form not submitting after AJAX call returns true

I'm using Google Phone validation library to check if a number is valid with an AJAX call. If the number isn't valid, I need the below function to prevent the form from submitting.

Currently it prevents the form from submitting correctly, but the form doesn't submit when it returns true. The alert at the true statement does indeed occur, but the form still doesn't submit. What am I missing?

$(document).ready(function(){
$('form#sellerForm').submit(validatePhoneNumber);
});

function validatePhoneNumber() {
var output = null;
var phoneNumber = $('#phone').val();
var node = document.getElementById('phoneOutput');
var country = $('#country').val();
if(country == -1){
  output = translateNoCountry();
  node.innerHTML = output;
  event.preventDefault();
  return false;
}
if(output == null){
  //AJAX to get country code from country for var regionCode;
  $.ajax({ type: "POST", 
    url: '/ajax/validate_phone.php', 
    data: {country: country},
    cache: false, 
    success: function(result) {
    var regionCode = jQuery.parseJSON(result);
      try {
        var phoneUtil = i18n.phonenumbers.PhoneNumberUtil.getInstance();
        var number = phoneUtil.parseAndKeepRawInput(phoneNumber, regionCode);
        var isNumberValid = phoneUtil.isValidNumber(number);
        if(!isNumberValid){//invalid number
            output = translateInvalidePhone();
        }
      } catch (e) {
        output = translateInvalidePhone();
      }
    if(output != null){
        node.innerHTML = output;
        event.preventDefault();
        return false;
    }else{
        alert('Hello world');
        return true;
    }
}
});
event.preventDefault();
return false;
}
}

Upvotes: 0

Views: 739

Answers (2)

Pankaj Dubey
Pankaj Dubey

Reputation: 824

don't use event.preventDefault(); at very last of your validatePhoneNumber() function

it prevent all the default postbacks

Upvotes: 0

Edwin Alex
Edwin Alex

Reputation: 5108

What is the use of,

event.preventDefault();
return false;

in the last line. I think it could be the problem.

Upvotes: 1

Related Questions