Take the 2-minute tour ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

I'm trying to get a javascript object turned into a php array.

I want to use results[j].distance.text and results[j].duratio.text in a php script. I'm using Google's API to get a duration and distance from a longitude and latitude.

But how do I get these client side data to server side(PHP)?

I think I need to make a AJAX call, but I have no clue how to do it.

Hope you guys can help me out. Thanks.

My code is below:

var map;
var geocoder;
var bounds = new google.maps.LatLngBounds();
var markersArray = [];
var origin1 = new google.maps.LatLng(<?php echo $lat;?>, <?php echo $long;?>);
var destinationA = 'Min adresse, Aarhus';
var destinationIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=D|FF0000|000000';
var originIcon = 'https://chart.googleapis.com/chart?chst=d_map_pin_letter&chld=O|FFFF00|000000';

function initialize() {
  var opts = {
    center: new google.maps.LatLng(<?php echo $lat;?>, <?php echo $long;?>),
    zoom: 10
  };
  map = new google.maps.Map(document.getElementById('map-canvas'), opts);
  geocoder = new google.maps.Geocoder();
}

window.onload = function calculateDistances(){
    var service = new google.maps.DistanceMatrixService();
  service.getDistanceMatrix(
    {
      origins: [origin1],
      destinations: [destinationA],
      travelMode: google.maps.TravelMode.DRIVING,
      unitSystem: google.maps.UnitSystem.METRIC,
      avoidHighways: false,
      avoidTolls: false
    }, callback);
};


function callback(response, status) {
  if (status != google.maps.DistanceMatrixStatus.OK) {
    alert('Error was: ' + status);
  } else {
    var origins = response.originAddresses;
    var destinations = response.destinationAddresses;
    var outputDiv = document.getElementById('outputDiv');
    outputDiv.innerHTML = '';
    deleteOverlays();

    for (var i = 0; i < origins.length; i++) {
      var results = response.rows[i].elements;
      addMarker(origins[i], false);
      for (var j = 0; j < results.length; j++) {
        addMarker(destinations[j], true);
        outputDiv.innerHTML += origins[i] + ' til ' + destinations[j]
            + ': ' + results[j].distance.text + ' tid til destination '
            + results[j].duration.text + '<br>';
      }
    }
  }
}

function addMarker(location, isDestination) {
  var icon;
  if (isDestination) {
    icon = destinationIcon;
  } else {
    icon = originIcon;
  }
  geocoder.geocode({'address': location}, function(results, status) {
    if (status == google.maps.GeocoderStatus.OK) {
      bounds.extend(results[0].geometry.location);
      map.fitBounds(bounds);
      var marker = new google.maps.Marker({
        map: map,
        position: results[0].geometry.location,
        icon: icon
      });
      markersArray.push(marker);
    } else {
      alert('Geocode was not successful for the following reason: '
        + status);
    }
  });
}

function deleteOverlays() {
  for (var i = 0; i < markersArray.length; i++) {
    markersArray[i].setMap(null);
  }
  markersArray = [];
}
share|improve this question

2 Answers 2

up vote 0 down vote accepted

You will have to make an AJAX call.

I suggest you take a look at jQuery. It provides you with an easy to understand implementation of how AJAX work and also helps you to handle the responses. (success, error etc.)

It provides a nice clear syntax, e.g:

$.ajax({
url:"handlePage.php",
data:{json object here},
dataType:"json",
success:function(jd){
     console.log("SUCCESS");   
}});

You can read more about it here:

jQuery Ajax Page

The best way to communicate data between PHP and JavaScript will be to make use of JSON.

JavaScript Objects can be presented as JSON objects. PHP consist of the functionality to decode these objects to arrays.

JSON Tutorial

For PHP to decode this, you will have to take a look at PHP's json_decode() and json_encode() functions:

PHP: json_encode manual PHP: json_decode manual

Hope this helps!

share|improve this answer

I haven't watched your full code but can answering by the following steps:

  • On submit or something, create a string array, separated by comma.
  • On server side split string in comma's and you have your php array

example:

<input name="tb1" class="testCreate" value="v1" />
<input name="tb2" class="testCreate" value="v2" />

<script>
  var result = $('.testCreate').map(function() {return this.value;}).get().join(',');

  $.ajax({
        url: "Path/to/file",
        type: "POST",
        cache: false,
        data: "value=" + result,
        success: function (html) {
            //Do somehting when done
        }
    });
</script>

And serverside get:

<?php
$array = implode(",", $_POST["value"]);
?>
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.