Reputation: 371
I am new to web development and I ran into an issue with a registration form that I'm building for our business. I am using this guide: http://css-tricks.com/using-ziptastic/. This is my first experience with AJAX and JSON and I just can't get the city and state to autofill as soon as I'm done typing in the zip code. Any solutions/suggestions/alternatives will be much appreciated. I set up a basic jsfiddle to test everything out: http://jsfiddle.net/7VtHc/
HTML:
<p>Zip Code: <input type="text" id="zip" /></p>
<p>City: <input type="text" id="city" /></p>
<p>State: <input type="text" id="state" /></p>
jQuery, etc.
$("#zip").keyup(function() {
var el = $(this);
if ((el.val().length == 5) && (is_int(el.val()))) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success)
$("#city").val(result.city);
$("#state").val(result.state);
});
}
});
Upvotes: 5
Views: 24598
Reputation: 1119
For India you can use pincode API for free, You can get the city with other information as JSON format.
Example: https://api.postalpincode.in/pincode/641001
Usage: https://api.postalpincode.in/pincode/${Your-pincode}
If any cors Policy occured means use this :
https://cors-anywhere.herokuapp.com/https://api.postalpincode.in/pincode/${Your-Pincode}
Example:
{
"Name": "Coimbatore",
"Description": null,
"BranchType": "Head Post Office",
"DeliveryStatus": "Delivery",
"Circle": "Tamilnadu",
"District": "Coimbatore",
"Division": "Coimbatore",
"Region": "Coimbatore",
"Block": "Coimbatore South",
"State": "Tamil Nadu",
"Country": "India",
"Pincode": "641001"
}
I am using this in Angular-8
Thanks.
Upvotes: 5
Reputation: 7301
This should work for you. http://jsfiddle.net/7VtHc/5/
I will added that ===
in JavaScript will check that type are the same. See Here.
There is no need to create an is_int()
function.
$(document).ready(function() {
$("#zip").keyup(function() {
var el = $(this);
if (el.val().length === 5) {
$.ajax({
url: "http://zip.elevenbasetwo.com",
cache: false,
dataType: "json",
type: "GET",
data: "zip=" + el.val(),
success: function(result, success) {
$("#city").val(result.city);
$("#state").val(result.state);
}
});
}
});
});
P.S. When you create a JSFiddle make sure you include jQuery from the menu on the right.
Upvotes: 7