-1
 $('form').submit(function(event){
    event.preventDefault();
    var userData = "https://maps.googleapis.com/maps/api/geocode/json?address="+$('input#city').val()+"&key=MY_API_KEY";
    console.log(userData);
    $.ajax({
      type: "GET",
        url : userData, 
        success: function(data){
            $.each(data['results'][0]['address_components'], function(key, value) {
                if(value["types"][0] == "postal_code"){
                    $('.alert-success').fadeIn(2000).html('Post/ZIP Code: '+value["long_name"]);
                }
            });
        }
    })
  });

So, I have this code, above, which is currently returning no error nor any results as desired.

It works fine as long as I put the entire 'https://maps.googleapis.com/maps/api/geocode/json?address=""&key=""' string in the url: "", section of the ajax, but when trying to pass my variable in it doesn't want to do anything.

From what I've found variables should pass through easily enough into the ajax call so I'm kind of lost.

geocodezip
  • 158,664
  • 13
  • 220
  • 245
Matt
  • 392
  • 1
  • 18

2 Answers2

0

You need to URL encode the string returned by $('input#city').val()

related question: JavaScript URL encode

Note: Not all geocoder records return members of the response array with a postal_code type (like for example a query for "New York, NY", it has multiple zip codes).

var userData = "https://maps.googleapis.com/maps/api/geocode/json?address=" 
                + encodeURIComponent($('input#city').val()) 
                + "&key=MY_API_KEY";
console.log(userData);
$.ajax({
  type: "GET",
  url: userData,
  success: function(data) {
  console.log(data);
    $.each(data['results'][0]['address_components'], function(key, value) {
      if (value["types"][0] == "postal_code") {
        $('.alert-success').fadeIn(2000).html('Post/ZIP Code: ' + value["long_name"]);
      }
    });
  }
});
Community
  • 1
  • 1
geocodezip
  • 158,664
  • 13
  • 220
  • 245
0

Your condition if (value["types"][0] == "postal_code") { is not working.

Check the returned data object via console.log.

Here is a working fiddle without it:

https://jsfiddle.net/1t82y0xa/

Sebsemillia
  • 9,366
  • 2
  • 55
  • 70