Solved

Javascript Callback or counter

Posted on 2014-04-08
3
390 Views
Last Modified: 2014-05-29
I have a working Google API geocoder that looks up the name of a county that a city is in and then puts the resulting list of counties into a new array.
However when testing I see that sometimes the order in which the counties are returned is different. I suspect what is happening is that all of the requests are being sent one right after the other but the API has different servers processing so sometimes the first city sent is the last one returned.  - is there a way to make this sequential? - this is a minor issue as I could just rebuild the address array in the order of returned values - just curous as to why it does what it does now.

The other issue i have is that if I have a long list of addresses the script moves ahead to my do something new part of the code before it finishes getting all of the address.

Do I need a callback or some type of counter to ensure that it gets all the responses before moving ahead?



<div id='myInfo1'>-</div>
<div id='myInfo2'>-</div>

$(document).ready(function () {
    var counties = [];
    var addresses = ["Orlando, Florida", "Boone,Iowa", "Ames,Iowa", "Des Moines,Iowa", "Jefferson,Iowa"];

    addresses.forEach(function (entry) {
        var myAddress = entry;
        var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=" + myAddress + "&sensor=true";
        console.log(geocodingAPI);
        $.getJSON(geocodingAPI, function (json) {
            $.each(json.results[0].address_components, function (i, jsonData) {
                level = jsonData.types[0];
                if (level.toLowerCase() == 'administrative_area_level_2') {
                    county = jsonData.short_name.substring(0, jsonData.short_name.length - 7);
                    counties.push(county);

                    console.log(counties.toString());
                    $('#myInfo1').html(counties.toString());
                    $('#myInfo2').html(counties.length);
                }

            });
        });
    });

});

//now do something with those results after all are received.

Open in new window

0
Comment
Question by:lvmllc
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
3 Comments
 
LVL 43

Expert Comment

by:Chris Stanyon
ID: 39987189
The reason they may come back out of sequence is simply down to the nature of AJAX calls. You make an AJAX call for each address in your list, but because the AJAX call is asynchronous, it doesn't wait around to finish before starting the next one. It may just be that the request for the first address takes slightly longer at the server than the request for the second request.

As for your code continuing to run - exactly the same reason as above - you make your calls Asynchronously, so your code doesn't stop and wait for the responses - it just carries on.

Normally, if you want to run code after the AJAX has finished, you make use of the 'Success' argument or .done() method

If you absolutely need your data returned 'in order' and only continue on with your code after all requests have finished, then you may have to change your AJAX request to a Synchronous one - the downside being it locks the browser while it's working.

As far as I'm aware there isn't a native callback mechanism for Google Geocoding
0
 

Author Comment

by:lvmllc
ID: 39987409
Chris - let me try something with the .done() method - I'll post back tomorrow on what I figure out along with any question I might still have for you.
0
 
LVL 49

Accepted Solution

by:
Roonaan earned 500 total points
ID: 40056953
The forEach method actually provides a second argument, which is the original index in the array.

Using that, you could insert the response in the same index as the addresses:

$(document).ready(function () {
    var counties = [];
    var addresses = ["Orlando, Florida", "Boone,Iowa", "Ames,Iowa", "Des Moines,Iowa", "Jefferson,Iowa"];

    addresses.forEach(function (entry, index) {
        //                             ^---- Use index argument from original array
        var myAddress = entry;
        var geocodingAPI = "http://maps.googleapis.com/maps/api/geocode/json?address=" + myAddress + "&sensor=true";
        console.log(geocodingAPI);
        $.getJSON(geocodingAPI, function (json) {
            $.each(json.results[0].address_components, function (i, jsonData) {
                level = jsonData.types[0];
                if (level.toLowerCase() == 'administrative_area_level_2') {
                    county = jsonData.short_name.substring(0, jsonData.short_name.length - 7);
                    counties[index] = county; //  INSERT AT ASSOCIATED INDEX

                    console.log(counties.toString());
                    $('#myInfo1').html(counties.toString());
                    $('#myInfo2').html(counties.length);
                }

            });
        });
    });
});

Open in new window

0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

I found this questions asking how to do this in many different forums, so I will describe here how to implement a solution using PHP and AJAX. The logical flow for the problem should be: Write an event handler for the first drop down box to get …
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

740 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question