1

I've wrote just a simple script, to collect some data and send it aftertwards via AJAX to an import script of my rails application.

After I didn't get any data, I've used the chrome debugger, but I still don't find the problem.

$('#poi_import').on('click',function () {

    var token = $('.temp_information').data('token');
    var auth_token = $('.temp_information').data('auth-token')

    poi = [];

    $('#service-helper input[type="checkbox"]:checked').each( function(element){
        var request = {
            placeId: $(this).attr('id')
        };

        var detail_service = new google.maps.places.PlacesService($('#tmp').get(0));
        detail_service.getDetails(request, function(place, _status) {
            write_poi(place);
        });
    });

    console.log("Now send the data")
    console.log(poi)

    jQuery.ajax({
        url: "/api/" + token + "/import",
        data: poi,
        type: "POST",
        beforeSend: function (xhr) {
            xhr.setRequestHeader('AUTHTOKEN', auth_token);
            xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
        }
    });

function write_poi(place) {

    //getting some information from "place"        

    poi.push({
      'name': name,
      'address': street,
      'city': city,
      'country': country,
      'phone': phone,
      'url': url
    });
    console.log(poi)
}

The console is logging followig lines:

Now send the data
[]
[Object]
[Object, Object]
[Object, Object, Object]

The script do the AJAX request, at first. After that it iterates the checked checkboxes...

Archer
  • 1,062
  • 1
  • 13
  • 32
  • 4
    `detail_service.getDetails()` is an *asynchronous* operation. Code immediately following the start of that operation is *very likely* to execute before that operation completes. – David Mar 28 '17 at 17:17
  • the question sounds dump, i think. But How can I make the script wait? – Archer Mar 28 '17 at 17:19
  • Do you have control over `detail_service.getDetails` if yes than make it `async:false` to make it work and it seem like `ajax` request right? – Curiousdev Mar 28 '17 at 17:19
  • @RickySpanish: `"How can I make the script wait?"` - You don't. Instead, you perform whatever tasks need to be performed in the callback where the asynchronous operation completes. So for example when you're looping over your array and making asynchronous operations, on the last iteration of that loop you might include a flag into that asynchronous callback which would tell it to invoke an additional function. – David Mar 28 '17 at 17:22
  • getDetails is in the Google Places API so I doubt he has much control over it. I would wrap each call to getDetails in a Promise adding to a collection and then .when() the collection at which point I would then run the jQuery.ajax() call. – Forty3 Mar 28 '17 at 17:22
  • Thank you! Now, I know the problem and I will find a solution to fix it :) – Archer Mar 28 '17 at 17:24

0 Answers0