chrisgrim's avatar

JS XHR failed loading: GET

Hi, I am using the following code to submit an ajax request to google maps. I am trying to send an address (#getaddy) to google and get the latitude and longitude from the response. Here is my code

let term = $("#getaddy").val();

$.ajax({
    url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(term) +'&key=GOOGLEKEY',
    type: 'get',
    success: function(data) {
        if (data.status === 'OK') {
            // Get the lat/lng from the response
            let lat = data.results[0].geometry.location.lat;
            let lng = data.results[0].geometry.location.lng;

            console.log("pass");

        }
    },
    error: function(msg) {
        console.log("fail");
    }
});

In the console I am getting the fail log and it says

VM108568:1 XHR failed loading: GET "https://maps.googleapis.com/maps/api/geocode/json?address=new%20york&key=GOOGLEKEY"

If I go directly to the url I can see the google response with the latitude and longitude. To cause even more confusion, every now and then it randomly says XHR loading finished and it works...? I am not sure what is happening.

0 likes
9 replies
Robstar's avatar

Google have their own API for this nowadays, you don;t have to make raw ajax requests. They have a "Places" service - https://developers.google.com/maps/documentation/javascript/places#place_search_requests

var map;
var service;
var infowindow;

function initMap() {
  var mapCenter = new google.maps.LatLng(-33.8617374,151.2021291);

  map = new google.maps.Map(document.getElementById('map'), {
    center: mapCenter,
    zoom: 15
  });

  var request = {
    query: 'Museum of Contemporary Art Australia',
    fields: ['photos', 'formatted_address', 'name', 'rating', 'opening_hours', 'geometry'],
  };

  service = new google.maps.places.PlacesService(map);
  service.findPlaceFromQuery(request, callback);
}

function callback(results, status) {
  if (status == google.maps.places.PlacesServiceStatus.OK) {
    for (var i = 0; i < results.length; i++) {
      var place = results[i];
      createMarker(results[i]);
    }
  }
}
chrisgrim's avatar

Hi @robstar

Do I need to call the map? Can I just use the query request with the users entered address? Do you know if this works with autocomplete as well? I tried updating my JS and I am getting new errors now that I am trying to trouble shoot.

Cronix's avatar

The code works fine and I just tested it again. Did you use your actual GOOGLEKEY here?

url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(term) +'&key=GOOGLEKEY',

Originally when I was helping you with this you posted your actual google key, and I told you that you should get a new one since you exposed yours to the public. When I wrote the sample code (which you copied here) I put GOOGLEKEY, which you should replace with your actual key. Did you?

chrisgrim's avatar

Hi @cronix !!

I did replace with my actual key. If I go directly to the url I see in the XHR finished loading (or failed to load) I can see the information back from google places.

I have been trying to test it but I can't for the life of me understand what is happening! I can search for "new orleans" and the first 2 attempts I get a failed loading. Then the third time it finishes. I was able to get something different when I added csrf to my site using

$.ajaxSetup({
    headers: {
        'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
    }
});

Then I get a new error

Access to XMLHttpRequest at 'https://maps.googleapis.com/maps/api/geocode/json?address=los%20angeles&key=GOOGLEKEY' from origin 'http://showbelow.test' has been blocked by CORS policy: Request header field X-CSRF-TOKEN is not allowed by Access-Control-Allow-Headers in preflight response.
VM181849 navSearch.js:22 fail
VM181804:1 XHR finished loading: OPTIONS "https://maps.googleapis.com/maps/api/geocode/json?address=los%20angeles&key=AIzaSyDi5THKxUVFMVrEMfl-2D03CCXNTkSavmI".

Thanks so much

Cronix's avatar

You don't need, or want, csrf for external requests. That only has an affect on requests made to your site, not external sites. Not sure what the issues is for you. I literally copied the code from your first post (substituting my key) and it works each time I try it.

Oh, I did also wrapped it in a domready event, but not sure if that would affect this, but it's a good thing to do in any case.

$(function() {
    // all the code from your first post here
});
chrisgrim's avatar

Hi @cronix Here is my js file, I do sorta have it inside a function. Though I don't have the $

function myClick() {
let latitude = document.getElementById("latitude").value;
if (latitude) {
     console.log(latitude);
  } else {

let term = $("#getaddy").val();

$.ajax({
    url: 'https://maps.googleapis.com/maps/api/geocode/json?address='+encodeURIComponent(term) +'&key=GOOGLEKEY',
    type: 'get',
    success: function(data) {
        if (data.status === 'OK') {
            // Get the lat/lng from the response
            let lat = data.results[0].geometry.location.lat;
            let lng = data.results[0].geometry.location.lng;

            console.log("pass");
        }
    },
    error: function(msg) {
        console.log("fail");
    }
});

}
}

function geo() {

autocomplete = new google.maps.places.Autocomplete(
    (document.getElementById('getaddy')), {
      types: ['geocode']
    });
  autocomplete.addListener('place_changed', addlatlong);
}
function addlatlong() {

var place = autocomplete.getPlace();

var latitude = place.geometry.location.lat();
var longitude = place.geometry.location.lng();

document.getElementById("latitude").value = latitude;
document.getElementById("longitude").value = longitude;
}

and my html

<form method="GET" id="my-form" action="/search" onsubmit="myClick()">
<input class="form-control" id="getaddy" type="text" placeholder="Search..." name="term" onFocus="geo()">
<input id="latitude" type="hidden" name="latitude">
<input id="longitude" type="hidden" name="longitude">
</form>

Does that look a lot different than yours?

Robstar's avatar

Have just come across a recent commit in a repo I've inherited, the below works fine (Jquery, yuck :/):


        $.ajax({
            url:    'https://maps.googleapis.com/maps/api/geocode/json',
            data:   {
                'address': 'YOUR QUERY',
                'key' : 'YOUR-API-KEY'
            },
            dataType: 'json',
            success: function (data) {
                if (data.status === 'OK') {
                    // ok
                }
            }
        });

I prefer Google Places API though.

chrisgrim's avatar

Hi @robstar

I looked at that google link and it seems like you need to already have the lat /long. Or am I reading that wrong?

Please or to participate in this conversation.