-1

I'm trying to access a geological website data using their API and Ajax to retrieve from it.

var location;
var titleName;
$(document).ready(function() {
  $('#earthquakes').click(function() {

    function getQuakes() {
      $.ajax({
        url: "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2014-01-02",
        function(data) {
          $.each(data.features, function(key, val) {
            var coord = val.geometry.coordinates;
            location = {
              lat: coord[0],
              lng: coord[1]
            };
            titleName = val.properties.title;
          });
        }
      });
    }
    console.log(location);
    console.log(titleName);
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button type="button" id="earthquakes">Click me</button>

In the result, when I click "earthquakes" button, it logs two lines:

"Location {hash: "", search: "", pathname: "/", port: "8888", hostname: "localhost"…}"

and

undefined

I seem to be targeting the right parameters with my function, but still, it doesn't get the data I need. Just for the reference here is their documentation: http://earthquake.usgs.gov/fdsnws/event/1/ But I believe the problem might be something else and I might be doing it wrong with variables and the way they are used.

Nebular Dust
  • 403
  • 1
  • 6
  • 17
  • apart from the correct answer from Darin Dimitrov you should find another name for `location`, as this is a global var already (the window.location), which you get output now. – Jeff Dec 05 '15 at 10:54
  • Look at [the URL you are accessing](http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2015-01-02) - it is spitting out "Error 400: Bad Request 120495 matching events exceeds search limit of 20000. Modify the search to match fewer events." – Quentin Dec 05 '15 at 10:59
  • It just returned a bunch of data, I think it gives an error from time to time but it's fine. – Nebular Dust Dec 05 '15 at 11:09

2 Answers2

1

It looks like you are trying to access those variables outside of the AJAX success callback. Remember that AJAX is asynchronous, so this callback could execute at a later time than your console.log statements. So basically if you want to retrieve those values, the best place to do so is inside the success callback and do not declare those 2 variables in the outer scope.

Also remember that you have a JSON array and not only a single earthquake data (unfortunately). So store those results in a javascript array variable:

$(document).ready(function() {
    $('#earthquakes').click(function () {
        function getQuakes(callback) {
            $.ajax({
                url: "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2015-01-02",
                function(data) {
                    var results = [];
                    $.each(data.features, function(key, val) {
                        var coord = val.geometry.coordinates;
                        var titleName = val.properties.title;
                        var quakeData = {
                            location: {
                                lat: coord[0],
                                lng: coord[1]
                            },
                            title: titleName
                        };

                        results.push(quakeData);
                    });

                    // Invoke the callback and pass it the results array
                    callback(results);
                }
            });
        }

        // Now call the getQuakes function and pass it a callback that
        // will be passed as argument the result array
        getQuakes(function(data) {
            // At this stage the result variable will contain an array
            // of javascript objects with location and title properties that
            // we constructed in our AJAX success callback. So here we can
            // do something with those results, like dumping them to the console
            console.log(data);
        });
    });
});

Obviously in this example we haven't handled the error event from the AJAX call which is something you probably want to do so that you can inform the users that something went wrong while retrieving this information from the remote server.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • OK, after I managed to format your code, I was able to see the scoping issue that you have. I have updated my answer with an example of how you could handle this situation properly. In your code you seem to be trying to access a variable before the AJAX call could have potentially completed so you will get undefined. If you are dealing with AJAX calls you should start thinking in terms of callbacks and not in terms of sequential function calls that return values. – Darin Dimitrov Dec 05 '15 at 11:02
  • But if those variables are inside of jquery function, there is no way I can use them outside of it, right? I plan to pass their values to google maps api which doesn't work with jquery so I need to have those variables as global. – Nebular Dust Dec 05 '15 at 11:05
  • No, you can't use those variables outside of this function and that's the whole point - the result is not available before this function has been invoked. So if you plan to pass those variables to google maps, it is inside this function that you will do so. Or you will pass a callback and it is inside this callback that you will invoke google maps. So basically you should stop thinking in terms of variables passing around but rather in terms of callbacks. – Darin Dimitrov Dec 05 '15 at 12:32
-1

try below code -

    var location;
    var titleName;
    $(document).ready(function() {
     $('#earthquakes').click(function (){
     $.ajax({
        url: "http://earthquake.usgs.gov/fdsnws/event/1/query?format=geojson&starttime=2014-01-01&endtime=2015-01-02",
        function(data){
        $.each(data.features, function(key, val) {
                var coord = val.geometry.coordinates;
                location = {
                    lat: coord[0],
                    lng: coord[1]
                };
                 titleName = val.properties.title;
            });        
          }
       });
       console.log(location);
       console.log(titleName);
      });
     });
Praveen Poonia
  • 745
  • 10
  • 18