-1

The code is supposed to add a click event where an infowindow opens on a marker with data from a PHP page and it "works" except the first infowindow opens blank (just says news in h1) and after that every other infowindow I open contains the stuff from the last marker. Can anyone tell me how to fix it?

//broken part
marker.addListener('click', function() {
    $.getJSON('articles.php/GET?geo='+ marker.title)
    .done(function(data, textStatus, jqXHR) {   
        $.each(data, function() {
            contentString=contentString + '<li><a href=' + data[counter].link + '>' +data[counter].title + '</a></li>' ;
            counter++;
        });         
    });

    contentString=contentString + '</ul></div>' ;
    var infowindow= new google.maps.InfoWindow({
        content: contentString  
    });

    infowindow.open(map, marker);
    counter=0 ;
    contentString='<div align="center"><h1>news</h1><br></div><div align="left" colour="blue"><ul>';
});
Mogsdad
  • 44,709
  • 21
  • 151
  • 275

1 Answers1

0

$.getJSON is asynchronous, you need to use the data inside its call back function, when/where it is available (inside the .done function).

marker.addListener('click', function() {
    $.getJSON('articles.php/GET?geo='+ marker.title)
    .done(function(data, textStatus, jqXHR) {   
        $.each(data, function() {
            contentString=contentString + '<li><a href=' + data[counter].link + '>' +data[counter].title + '</a></li>' ;
            counter++;
        });         
        contentString=contentString + '</ul></div>' ;
        var infowindow= new google.maps.InfoWindow({
            content: contentString  
        });

        infowindow.open(map, marker);
        counter=0 ;
        contentString='<div align="center"><h1>news</h1><br></div><div align="left" colour="blue"><ul>';

    });
});
geocodezip
  • 158,664
  • 13
  • 220
  • 245
  • Many thx for that, thats how i initialy had it but it kept giving me errors on the page, i suppose i just had some syntax problem cuz that worked fine. – Pedro Barros Jan 07 '16 at 23:11