0

EDIT: So I ended up with this code here, but as always, can't get it to work properly. Basically it has to check that all input fields are filled, once this check is true, it calls the JSON url to check validity of the VAT number. If the VAT number check returns true, submits the form, else it inform the customer that there is an error and let the customer choose if to ignore the exception (then submits) or cancel submission and stay on the page. Here is the JS code, and below is the JSON returned from the call.

$(document).ready(function() {
$('#create_customer').submit(function(){
 var canSubmt = true;
 $("form#create_customer :input").each(function(){
 var input = $(this);
 if($(input).val() == '') {
 $(input).css("border",'1px solid red');
 canSubmt = false;
 }else{
 $(input).css("border",'1px solid #000');
 }
 });
 if(!canSubmt){ $("#errMsg").text("Errors detected! Please check your form and try again.").show().fadeOut(7000); return canSubmt; }
 var vatNum = document.getElementById('VatNum').value;
 var validVat;
 var vatConfirm;
 $.getJSON("http://apilayer.net/api/validate?&access_key=<api-key>&vat_number="+vatNum, function(response) {
 validVat = response.valid;
 })
 .fail(function(){
 console.log("failed");
 });
 if (!validVat) { vatConfirm = confirm("Your VAT number doesn't seem to be valid or in a correct format!\nDo you wish to continue anyway?"); }
 if (!vatConfirm) { canSubmt = false; }
 return canSubmt;
});

});

and the JSON data, from which I only need the "valid" key:

{ "valid": true, "format_valid": true, "query": "LU26375245", "country_code": "LU", "vat_number": "26375245", "company_name": "AMAZON EUROPE CORE S.A R.L.", "company_address": "5, RUE PLAETIS L-2338 LUXEMBOURG" }

any idea on how to get this working?

asked May 18, 2017 at 14:05
7
  • 3
    is that your actual access key? you may want to remove that Commented May 18, 2017 at 14:07
  • sorry I just saw the "validVat = true" mistyping - the second one should go out one bracket, Commented May 18, 2017 at 14:08
  • 1)ajax is asynchronous 2)validVat scope is inside the ajax function so it will undefined on the line "return ..." Commented May 18, 2017 at 14:09
  • no I mean in your second code block, your url variable contains the api key Commented May 18, 2017 at 14:09
  • also you can do it in a callback like so $(document).ready(function(callback) {... callback} where callback is the ajax call Commented May 18, 2017 at 14:10

1 Answer 1

3

Ther're two issues:

  • Ajax is asynchronous, so before it returns the value of validVat execution probably has already reached the return statement
  • validVat's scope is inside the ajax function so it will undefined on the line "return ..."

The simplest thing you could do, is to make the ajax request synchronous, see following please:

var validVat = false;
$.ajax({
 var vatNumber = document.getElementById("VatNum").value;
 url: 'http://apilayer.net/api/validate?access_key=6ab1579cc9e968a65429d7f351375f35&vat_number='+vatNumber, 
 dataType: 'jsonp',
 async: false,
 success: function(json) {
 // Access and use your preferred validation result objects
 if (!json.valid) {
 var r = confirm("Your VAT number doesn't seem to be valid or in a correct format!\nDo you wish to continue anyway?");
 if (r == true) {
 validVat = true;
 } else {
 validVat = true;
 }
 }
 }
 });
 return validVat;

The best thing instead, should to use the callback function in order to submit the form or do anything you need after the response of ajax request.

Here's a complete example with a mock of ajax request, please see following:

var validated = false;
$("form").submit(function( event ) {
 
 if(!validated){
 event.preventDefault();
 
 var mock = {
 ajax: function() {
 return mockAjax({
 success: $("#test").val() === "correct",
 response: { ok: $("#test").val() === "correct" },
 timeout: 500
 });
 }
 };
 mock.ajax()
 .done(function(valid) {
 if(valid) {
 $("#err").text("Validated... do submit").show();
 validated = true;
 return $("form").submit();
 } else {
 event.preventDefault();
 }
 })
 .error(function(json) {
 $("#err").text("Not valid!").show().fadeOut(1000);
 });
 }
});
function mockAjax(options) {
 var that = {
 done: function done(callback) {
 if (options.success)
 setTimeout(callback, options.timeout, options.response);
 return that;
 },
 error: function error(callback) {
 if (!options.success)
 setTimeout(callback, options.timeout, options.response);
 return that;
 }
 };
 return that;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>Type 'correct' to validate.</p>
<form action="javascript:console.log( 'success!' );">
 <div>
 <input id="test" type="text">
 <input type="submit">
 </div>
</form>
<span id="err"></span>

I hope it helps you, bye.

answered May 18, 2017 at 14:14
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks Ale, that helps a bit understanding how Ajax works, but being a total newbie with it I'm not able to apply this code to my needs. However, i did end up with a simpler code after researching the forums and that seem to do everything I need but the API call - running it alone, tho, it does work. How strange is that?

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.