Stefano
Stefano

Reputation: 47

Ajax JSON malfunction

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?

Upvotes: 0

Views: 117

Answers (1)

Alessandro
Alessandro

Reputation: 4472

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.

Upvotes: 3

Related Questions