Wait for async return in editor.on("preSubmit", ...

Wait for async return in editor.on("preSubmit", ...

alphadadalphadad Posts: 12Questions: 6Answers: 0
edited March 2016 in Editor

Hiya ...

I'm trying to add to the post data in an editor "create" action with an async call to the Google map API to add Lat and Lng values to the new client as follows ....

editor.on('preSubmit', function(e, data, action){
        if (action === 'create') {
            var gAddress = $('#DTE_Field_mytable-Address1').val() + ', ' + $('#DTE_Field_mytable-CityID :selected').text();
            var gLatLng = function(){
                var geo = new google.maps.Geocoder();
                geo.geocode({'address': gAddress}, function(results, status) {
                if (status == google.maps.GeocoderStatus.OK) {
                    return [results[0].geometry.location.lat(), results[0].geometry.location.lng()];
                }
              });
            };
            data.data[0].mytable.gLat = gLatLng[0];
            data.data[0].mytable.gLng = gLatLng[1];             
            console.log(JSON.stringify(data));
            console.log(gAddress);
        }
    });

... the problem is that the "editor.on" function returns before the async call to the Google Maps API returns and the LatLng values never get added to the data param.

Thoughts?

Dave

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 63,498Questions: 1Answers: 10,471 Site admin
    Answer ✓

    Hi Dave,

    I'm afraid you can't perform an async action inside preSubmit since it expects any processing to be synchronous.

    What you could possibly do is return false from that event handler when it goes to get the data, and then in the callback from the Google API call submit() again. You'd need to add some logic to check if the preSubmit is coming from the user submitting the form or the callback from the lookup.

    Its a little messy that, but I think that's one of the few option at the moment. Another would be to have the server-side script do the lookup.

    Regards,
    Allan

This discussion has been closed.