Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

Making an ASYNC call to a remote script / live feedback on form

Posted on 2016-09-16
8
Medium Priority
?
42 Views
Last Modified: 2016-10-11
I have a script running on my server that takes a VAT number delivered via URL, and checks it

(note the url is broken into two values the first 2 letters and all the numbers behind it as VIES (vat checker) uses those two variables. The script works fine (I have included it below the question for reference). To call it..

 
  (website)/vatchecker.php?vat=xx1234567

Open in new window


and it returns {“is_valid”:true} or  {“is_valid”:false}

Now, I have a form on my site with the following fields

    <input type=“text” name=“vat_number” id=“vat_number”>
    <input type=“text” name=“vat_number_confirmed” id=“vat_number_confirmed”>
    and
    <input type=“hidden” name=“vat_ok” id=“vat_ok” value=“0”>

Open in new window


and finally a message box

    <div id=“vat-ok” style=“display:none;”>Your VAT is ok</div>
    <div id=“vat-error” style=“display:block;”>Your VAT is not valid</div>

Open in new window



The site is PHP and I have already done chunks of the code

My scenario, as soon as characters are typed in the field vat_number I want to do an async called to vat_checkers.php with the ongoing value being typed in vat_number and check it. This should be live, and constant everytime there is an input.. and when its true, it gets saved, and does a few others thing listed below.

i.e

    $(‘#vat_number’).on('input', function() {
        // do my check on vat checker.php with vat=$(“#vat_number”).val()
    
    	// when returned JSONresponse is {“is_valid”:true}
    
    		{
    			document.getElementById(“vat_ok”).value = “1”;
    			document.getElementById(“vat_number_confirmed”).value = $(“#vat_number”).val()
    			$(“#vat_number”).attr(“disabled”, true);
    			$(“#vat-ok”).show();
    			$(“#vat-error”).hide();
    	
    	});

Open in new window


Can anyone advise how to put all these blocks together into a working method as my brain will not grasp this final link. Thank you in advance for any assistance

For reference... the vat script VIES VAT Validator on GitHub

   
 <?php
    
    class VatValidator
    {
        public $response;
        protected $soap;
    
        // WSDL VIES Url Service.
        protected static $url_vies = 'http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl';
    
        // Valid european countries ISO codes.
        protected static $european_countries = array(
            'AT', 'BE', 'BG', 'CY', 'CZ', 'DE', 'DK', 'EE', 'ES', 'FI', 'FR', 'GB', 'GR', 'HU', 'IE', 'IT', 'LT', 'LU', 'LV', 'MT', 'NL', 'PL', 'PT', 'RO', 'SE', 'SI', 'SK'
        );
    
        public function __construct ()
        {
            $this->soap = new SoapClient( self::$url_vies );
        }
    
        /**
         * Check if it's a valid vat number.
         */
        public function checkVat ( $country, $number )
        {
            $response = array( 'is_valid' => false );
            $vat = $this->prepareVat( $country, $number );
            if ($vat)
            {
                $this->response = array( 'is_valid' =>$this->soap->checkVat( $vat )->valid );
            }
            return json_encode( $this->response );
        }
    
        /**
         * Checks that there are all needed params ( Code Country and number );
         */
        protected function prepareVat( $country, $number )
        {
            try
            {
                if ( empty( $country ) || empty( $number ) )
                {
                    throw new Exception( "Both 'country' and 'number' params are mandatory" );
                }
    
                if ( !in_array( $country, self::$european_countries ) )
                {
                    throw new Exception( "Invalid country" );
                }
    
                $vat = array(
                    'vatNumber'		=> $number,
                    'countryCode'	=> $country,
    
                );
                return $vat;
            }
    
            catch( Exception $e )
            {
                $this->response = array( 'error_message' => $e->getMessage() );
                return false;
            }
        }
    }
    
    // API Call
    $vies = new VatValidator();
    
    if ($_GET['vat']) {
        $vat = $_GET['vat'];
        $country = substr($vat, 0, 2);
        $number = substr($vat, 2);
    } else {
        $country = "";
        $number = "";
    }
    
    $vies->checkVat( strtoupper( $country ), $number);
    $response = json_encode( $vies->response);
    echo $response;
    ?>

Open in new window

0
Comment
Question by:mvwmail
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
  • 2
8 Comments
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41802376
It looks like you edited your code samples in Microsoft Word.  The angled quotes around “vat_ok” are called 'smart quotes' and are not acceptable substitutes for standard ASCII single and double quotes.  That usually cause your code to be mis-interpreted.
0
 
LVL 3

Author Comment

by:mvwmail
ID: 41802381
That snippet is in no way representative of anything I have written / tested and was just a poor code example I threw together in textwrangler. 10/10 for the spot but not quite the answer I was seeking as that code is incomplete hence why I am here

Sadly, I cant seem to edit the question body to correct the snippet
0
 
LVL 84

Expert Comment

by:Dave Baldwin
ID: 41802393
Just post a correct version then.  With 'smart quotes', the code can't work.
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 3

Author Comment

by:mvwmail
ID: 41802400
HI Dave, I appreciate you taking time to answer.. but to reiterate.. I have come to get assistance on how to get this to work and not how to correct a completely bogus sample.. which if I could edit the question, I would remove as it is becoming the focus of my request for assistance and it likely not even a suitable starting base for any function.

Push comes to shove, look like I am going to have to delete / close this question as there appears to be no way whatsoever to edit it which is very frustrating
0
 
LVL 3

Author Comment

by:mvwmail
ID: 41802406
heh heh, just fed the code into PHPStorm, you can imagine how many underlines and orange popped up

ok here is where I am at so far

var searchRequest = null;

$(function () {
    var minlength = 3;

    $("#jform_company_vat_tmp").keyup(function () {
        var that = this,
            value = $(this).val();

        if (value.length >= minlength ) {
            if (searchRequest != null)
                searchRequest.abort();
            searchRequest = $.ajax({
                type: "GET",
                url: "(website)/vies.php",
                data: {
                    'vat' : this
                },
                dataType: "text",
                success: function(msg){
                    //we need to check if the value is the same
                    if (value==$(that).val()) {
                        document.getElementById("vat_ok").value = "1";
                        document.getElementById("vat_number_confirmed").value = $("#jform_company_vat_tmp").val()
                        $("#jform_company_vat_tmp").attr("disabled", true);
                        $("#vat-ok").show();
                        $("#vat-error").hide();
                    }
                }
            });
        }
    });
});

Open in new window

0
 
LVL 84

Assisted Solution

by:Dave Baldwin
Dave Baldwin earned 1000 total points (awarded by participants)
ID: 41802430
If you're not getting the proper response, I would comment out lines 22 and 28 above so that the response is always displayed at this point.
0
 
LVL 34

Accepted Solution

by:
Slick812 earned 1000 total points (awarded by participants)
ID: 41803201
greetings mvwmail, , , , You do not seem to have any correct arrangement of the javascript that's trying to do the AJAX send and receive . You do not have the success function in any code arrangement to work. Also you send back from ajax PHP server a JSON text string, BUT in your AJAX parameters you use a return dataType of "text", which I guess is incorrect? But can still be used for such a simple AJAX server return.

I can not test this code below, but it is closer to being workable than your version -
var searchRequest = null;

$(function () {
    var minlength = 3;

    $("#jform_company_vat_tmp").keyup(function () {
       // var that = this,
            value = this.value;

        if (value.length >= minlength ) {
            if (searchRequest != null)
                searchRequest.abort();
			
              var ajParam = {
                type: "GET",
                url: "(website)/vies.php",
                data: {vat : value},
                dataType: "text" // You use the dataType as text, but you send back JSON
                }
			  
              searchRequest = $.ajax( ajParam ).done(function( msg ) {
                    //if you use the dataType:"text" then test the msg as a string value '{"is_valid":true}'
                    if (msg == '{"is_valid":true}') {
                        document.getElementById("vat_ok").value = "1";
                        document.getElementById("vat_number_confirmed").value = value;
                        $("#jform_company_vat_tmp").attr("disabled", true);
                        $("#vat-ok").show();
                        $("#vat-error").hide();
                    }
                });
            
        }
    });
});

Open in new window


as to the SERVER php code, sisce you just need true or false, you can might can change the operations to -
$vies = new VatValidator();
    
    if ($_GET['vat']) {
        $vat = $_GET['vat'];
        $country = substr($vat, 0, 2);
        $number = substr($vat, 2);
        $vies->checkVat( strtoupper( $country ), $number);
        if($vies->response) 
          echo 'true'; 
          else echo 'false';

    } else {
        echo 'false';
    }
    

Open in new window


so it sends back the string "true" or the string "false" .
and in the javascript you can just test for "true , like -
         if (msg == "true") {
0
 
LVL 34

Expert Comment

by:Slick812
ID: 41838067
Question has been abandoned, Points split for possible solutions
0

Featured Post

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

When it comes to write a Context Sensitive Help (an online help that is obtained from a specific point in state of software to provide help with that state) ,  first we need to make the file that contains all topics, which are given exclusive IDs. …
Many old projects have bad code, but the budget doesn't exist to rewrite the codebase. You can update this code to be safer by introducing contemporary input validation, sanitation, and safer database queries.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
Suggested Courses

636 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question