PHP Magento Tips

Autofill City & State from Zip Code with Ziptastic in Magento Checkout Page

Rate this posting:
{[['']]}

Most address fields on web forms ask for city, state, and zip. If People enter wrong zipcode but correct city and state, then it might be possible that your order may be not reach on time or can’t reach to your location. We can not predict right state and city of customer if he enter wrong zipcode in checkout page.

To solve this problem we need a proper API which cought up correct city and state based on entered Zip Code.  Ziptastic, a free API is one of the best tool which does the same thing. Let's use it.

open app/design/frontend/yourtemplate/default/template/persistent/checkout/onepage/billing.phtml

add below code at the end where your Javascript start:

<script type="text/javascript">
//<![CDATA[
    //setup before functions
    jQuery( document ).ready(function() {
    var typingTimer;                //timer identifier
    var doneTypingInterval = 1000;  //time in ms, 1 second for example
    var input = jQuery('[id="billing:postcode"]');
    var city = jQuery('[id="billing:city"]');
    
    
    //on keyup, start the countdown
    input.on('change', function () {
      clearTimeout(typingTimer);
      typingTimer = setTimeout(doneTyping, doneTypingInterval);
    });
    //on tab, start the countdown
    input.on('keydown', function (e) {
      var keyCode = e.keyCode || e.which;
      if (keyCode == 9 && input.val() != '') { 
          e.preventDefault(); 
          clearTimeout(typingTimer);
          typingTimer = setTimeout(doneTyping, doneTypingInterval);
      }
    });
    on keydown, clear the countdown 
    input.on('keydown', function () {
      clearTimeout(typingTimer);
    });
    //on select all, clear the countdown 
    input.on('keydown', function (e) {
        if ( e.ctrlKey && ( String.fromCharCode(e.which).toLowerCase() === 'a') ) {
              clearTimeout(typingTimer);
        }
    });
    //user is "finished typing," do something
    function doneTyping () {
      jQuery.support.cors = true;
      var el = jQuery(input).val();
      if (el.length === 5 && el != '') {
          jQuery.ajax({
              url: "http://zip.getziptastic.com/v2/US/" + el,
              async: false,
              cache: false,
              dataType: "json",
              type: "GET",
              beforeSend: function() {
                  jQuery('#zip-loader').show();
                  jQuery('[id="validation-custom-advice"]').hide();
                  jQuery('[id="validation-correct-advice"]').hide();
              },   
              complete: function(){
                  jQuery('#zip-loader').hide();
                 },
              error: function(xhr, textStatus, errorThrown){
                  if (xhr.status == 404) {
                      jQuery('[id="billing:region_id"]').find('option:selected').removeAttr('selected');
                      jQuery(city).val('');
                      jQuery('[id="validation-custom-advice"]').hide();
                      jQuery('[id="validation-correct-advice"]').show();
                  }
              },     
              success: function(result, success) {
                  jQuery('[id="validation-correct-advice"]').hide();
                  jQuery('[id="validation-custom-advice"]').hide();
                  jQuery('[id="advice-required-entry-billing:city"].validation-advice').hide();
                  jQuery(city).val(result.city);
                  jQuery('[id="billing:region_id"] option').each(function() {
                            if(jQuery(this).text() == result.state){
                                jQuery(this).prop("selected","selected");
                            } else {
                                jQuery(this).removeAttr("selected","selected");
                            }
                    });
              }
          });
      }
      if (el != ''){
      if (el.length > 5 || el.length <5 ) {
          jQuery('[id="validation-correct-advice"]').hide();
          jQuery('[id="billing:region_id"]').find('option:selected').removeAttr('selected');
          jQuery(city).val('');
          jQuery('[id="validation-custom-advice"]').show();
          return false;
      }
      }
    }
    });
//]]>
</script>


Now check your checkout/onepage page. Enter Correct US zip code and it will fill your State and City data accordingly. Write down your comment below for better suggestion
Tag : Magento
4 Comments On "Autofill City & State from Zip Code with Ziptastic in Magento Checkout Page"

I really appreciate information shared above. It’s of great help. If someone want to learn Online (Virtual) instructor lead live training in Typo3, kindly contact us http://www.maxmunus.com/contact
MaxMunus Offer World Class Virtual Instructor led training on Typo3. We have industry expert trainer. We provide Training Material and Software Support. MaxMunus has successfully conducted 100000+ trainings in India, USA, UK, Australlia, Switzerland, Qatar, Saudi Arabia, Bangladesh, Bahrain and UAE etc.
For Demo Contact us:
Name : Arunkumar U
Email : arun@maxmunus.com
Skype id: training_maxmunus
Contact No.-+91-9738507310
Company Website –http://www.maxmunus.com


This comment has been removed by the author. - Hapus

This is my code : http://pasted.co/8e229af3, not getting city and state after enter zipcode.

i use this code ; but not getting city and state after enter zip code
i use rwd theme in magento 1.9.3 give any vedio for integeration of this api

Back To Top