user4691546
user4691546

Reputation:

passing php array to javascript using ajax

I'm building something with Google Maps and Instagram. I'm trying to send the coordinates of the Instagram photos from my PHP file to my JavaScript file using AJAX. I basically have no idea how to handle this on the JavaScript side.

This is what my index.php file looks like:

<?php

$jsonText= file_get_contents("");

$instagram = json_decode($jsonText);


foreach ($instagram->data as $photo) {

$longitude = $photo->location->longitude;
$latitude = $photo->location->latitude;
$picture = $photo->images->thumbnail->url;

$results = array($latitude, $longitude, $picture);
echo json_encode($results, true);
}
?>

My js file looks like this:

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

function initialize() {
var mapOptions = {
    zoom: 5,
    center: new google.maps.LatLng(45.525961, 15.255119)
};
var map = new google.maps.Map(document.getElementById('map-canvas'),
    mapOptions);



$.ajax({
    url: 'index.php',
    dataType: 'json',
    success: function(data) {

        var location = new google.maps.LatLng();

        var marker = new google.maps.Marker({
            position: location,
            map: map,
            title:"Where the photo was taken.."
        });
    }
})

}

Upvotes: 0

Views: 115

Answers (1)

Himanshu
Himanshu

Reputation: 212

First of all, I would suggest you not to share your API Key/Access Token publicly.

I made slight changes to your code. This is the ajax call now,

$.ajax({url: 'test.php'}).done(function(data) {
            // alert(data);
            for (var i = data.length - 1; i >= 0; i--) {
                for (var j = data[i].length - 1; j >= 0; j--) {
                    $("#someElement").append(data[i][j]);
                };
            };
        }
);

You can use the data as you wish.

Upvotes: 1

Related Questions