HTML form that populates the city and state given the zip code
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

What I want: an html form with zip, city, and state fields. When a zip code is entered, the form should automatically populate the city and state fields via an ajax call to an external service, based on the zip code.

Here are the requirements:

  • It should make an AJAX call to an external service, perhaps this one:
  • The call should be made once the zip is a valid length (5 digits, or the longer format) and format (all numbers)
  • US support only is fine
  • jQuery is fine (but please ask before using other libraries)

Let me know if you have any questions before posting. Thanks in advance!

Plain JavaScript or jQuery & similar are possible?
kpower 9 years ago
Yes, plain JS or jQuery are fine (but please do not use another library). I'll update the question.
bevan 9 years ago
awarded to alixaxel

Crowdsource coding tasks.

3 Solutions

Winning solution

Here is my solution:

It's a single file, but it was necessary a bit of server-side code (in this case PHP) to overcome the Access-Control-Allow-Origin errors, since WebserviceX.NET doesn't return data in JSON-P. I've implemented client-side and server-side validation for the Zip + 4 so it should run smoothly.

The only requirement is that you name the file zip.php, if you change the file name (or split the server-side from the client-side code) you should update line 151 as well.

Thanks for the great solution!
bevan 9 years ago

The fiddle alone will not work because you need an external PHP file to read the web service and return the output to you as the URL fails the Same origin policy

main file - check this fiddle

<script type="text/javascript">
$("input[name='zip']").bind('change keyup', function(){

    var zipcode = $(this).val();
    var isValidZip = /(^\d{5}$)|(^\d{5}-\d{4}$)/.test(zipcode);
    var webservice = "";

            url: 'proxy.php?url=' + webservice + '?USZip=' + zipcode,
            datatype: 'xml',
            success: function(data){



        <label>Zip Code : </label>
        <input type="text" name="zip" />
        <span class="loading">loading..</span>
        <label>City: </label>
        <input type="text" name="city" />
        <label>State : </label>
        <input type="text" name="state" />


<?php echo @file_get_contents($_GET['url']);?>

Thanks for the solution! I appreciate the js fiddle and the clear and concise code.
bevan 9 years ago

css: style.css

No php script, just an ajax call. Everything in HTML.

View Timeline