Frank Eno
Frank Eno

Reputation: 2649

Showing JS array in div from AJAX call

I'm trying to show an array of values form an ajax call after a php query. The Chrome console shows me the array which looks formatted the way I need:

[["Fjeldrype",10,66.93786,-53.66025575],
["Isbj\u00f8rn",50,66.938302219,-53.6697265625],
["Hvalros",30,66.943385800,-53.66972494375],
["Fjeldrype",10,66.9514791099,-53.720629459375],
etc...

The values of my array are name, points, latitude and longitude coordinates, as shown above.

The problem is that I cannot show the name value in my div, I can only show the complete array, here's my PHP query:

$monstersData = array();

try {
    $query = new ParseQuery("Monsters");
    $mArray = $query->find();    

    for ($i = 0;  $i < count($mArray); $i++) {
        // Get Parse Object
        $mObj = $mArray[$i];

        // Get name
        $mName = $mObj->get('name');
        // Get location
        $mLocation = $mObj->get('location');
        $mLat = $mLocation->getLatitude();
        $mLng = $mLocation->getLongitude();
        // Get points
        $mPoints = $mObj->get('points');

        // create array
        $monstersData[] = [$mName, $mPoints, $mLat, $mLng]; 
        ;          
    }
    echo json_encode($monstersData);

And here's my JS code in index.html:

<script>

$.ajax({
    url: "query-monsters.php", 
    success: function(result){ 
        console.log(result);
        addMonstersOnMap(result);
}});


function addMonstersOnMap(monsters) {

    var centerCoords = new google.maps.LatLng(66.93828964, -53.64523124);

    var mapOptions = {
                zoom: 2,
                scrollwheel: true,
                center: centerCoords,
                mapTypeId: google.maps.MapTypeId.ROADMAP
            }

            var map = new google.maps.Map(document.getElementById('mapCanvas'), mapOptions);

            for (var i =0; i<monsters.length; i++) {
                // HERE'S WHERE I NEED TO SHOW THE NAME VALUE AT INDEX 0 OF EACH ROW OF MY ARRAY:
                document.getElementById("monstersList").innerHTML = monsters[i][0]; 
            }

            var marker, i;
            var infowindow = new google.maps.InfoWindow();

            // Add marker for each Monster
            for (i = 0; i < monsters.length; i++) {

                marker = new google.maps.Marker({
                    position: new google.maps.LatLng(monsters[i][2], monsters[i][3]),
                    map: map,
                    icon: 'assets/images/' + monsters[i][0] + '.png'
                });


                // click function to marker, pops up infowindow
                google.maps.event.addListener(marker, 'click', (function(marker, i) {
                    return function() {
                        infowindow.setContent(monsters[i][0]);
                        infowindow.open(map, marker);
                    }
                })(marker, i));

            }// end FOR loop

    google.maps.event.addDomListener(window, 'load', initialize);

}

  </script>

Unfortunately, what I get on my page is just an empty value like this: []

Here's a screenshot of my page as well:

enter image description here

So I guess I'm doing something wrong while formatting my result array from ajax. In other words, I need to get each single value of each row of my monsters array in my JS function, like monsters[i][0], or monsters[i][1], etc.

Upvotes: 2

Views: 282

Answers (1)

Iain Fraser
Iain Fraser

Reputation: 6738

The problem is in this piece of code here:

for (var i =0; i<monsters.length; i++) {
    // HERE'S WHERE I NEED TO SHOW THE NAME VALUE AT INDEX 0 OF EACH ROW OF MY ARRAY:
    document.getElementById("monstersList").innerHTML = monsters[i][0]; 
}

On every iteration of your loop, you're replacing the whole HTML of your monstersList div with that particular value. As you've indicated you're using jQuery, how about the following:

var $monstersList = $('#monstersList');
for (var i =0; i<monsters.length; i++) {
    $monstersList.append(monsters[i][0]);
}

Although that will just concatenate all your monsters values together into one big string. You probably want each monster in it's own element, something like this:

var $monstersList = $('#monstersList');
for (var i =0; i<monsters.length; i++) {
    var $monsterElement = $('<p>').html(monsters[i][0]);
    $monstersList.append($monsterElement);
}

Additionally, you will find that your ajax callback just sends a string through to your addMonstersOnMap function and not the array like you expect. Try parsing the result first, like this:

$.ajax({
    url: "query-monsters.php", 
    success: function(result){ 
        var data = JSON.parse(result);
        console.log(data);
        addMonstersOnMap(data);
}});

Upvotes: 2

Related Questions