javascriptjqueryajaxgeocodinggeocomplete

Use geocomplete function after ajax event


I have a button that adds an input box where you can type an address. For the address, I'm using the geocomplete plugin. In all input boxes that were not generated with ajax the geocomplete works. If the input was generated by ajax, it doesnt.

This is my code to generate the input box:

$('.add-drop').on('click', function(){  
     $.ajax({
         url : '/ajax/get-location-input',
         success : function(data){   
            $('#additional-drop').append(data);
        } 
    }); 
});

This is my geocomplete code:

$(".get-location").geocomplete({
    details : "form",
    types : ["geocode", "establishment"]
  }).bind("geocode:result", function(event, result){  
      console.log(result);
});

The problem is not with the class. I was trying to do something like $(".get-location").on("geocomplete"... but it wasn't working. Any idea? Thanks


Solution

  • AJAX is Asynchronous (Asynchronous JavaScript and XML) That means it might execute after the main code has been finished processing

    $.ajax({
        url: '/ajax/get-location-input',
        success:function(data){   
            alert(data);
        } 
    });
    
    alert('Hi ');
    

    In this case, Hi will alert first, then data. In your case, the inputs might not even be generated yet and so the geolocation code won't see them

    The correct code:

    $.ajax({
        url: '$('#additional-drop').append(data);',
        success:function(data){   
            $('#additional-drop').append(data);
    
            $(".get-location").geocomplete({
                details: "form",
                types: ["geocode", "establishment"]
            });
    
        } 
    });
    

    Will make the code run after the data has been fetched from the server


    This is me recommended way to do this:

    (function () {
    
        $.fn.addGeolocation = function () { this.geocomplete({ details: "form", types: ["geocode", "establishment"] }).bind("geocode:result", function(e, a){ console.log(a); }); }
    
        $.get('/ajax/get-location-input', function (a) {
            $('#additional-drop').append(data);
    
            $(".get-location").addGeolocation();
    
        });
    
        /* You may or may not need this */
        window.onload = function () { $(".get-location").addGeolocation(); }
    
    }());