0

I'm very new to coding and am creating an online system. Part of the system I have included Google Distance Matrix API which is JavaScript, whereas most of my other code is HTML or PHP. Unfortunately, I need the distance (which is calculated in JavaScript) to be in my PHP code so I can play about with it. I read I could use AJAX? I'm not terribly sure about what I'm doing but I had a go.

Before the page that includes the Google Map, there is a form. This means I have to use SESSION variables to move the data from the page before the Google page, to two pages after the Google page.. this is also where my Google script gets it's two locations to find the distance between. Which all works fine, I think.

PHP on Google page:

$date = $_POST['date'];
$time = $_POST['time'];
$length = $_POST['length'];
$numberofpeople = $_POST['numberofpeople'];
$useofbus = $_POST['useofbus'];

session_start();
$_SESSION['time'] = $time;
$_SESSION['date'] = $date;
$_SESSION['length'] = $length;
$_SESSION['numberofpeople'] = $numberofpeople;
$_SESSION['pickuplocation'] = $pickuplocation;
$_SESSION['destination'] = $destination;
$_SESSION['useofbus'] = $useofbus;


$pickuplocation = $_POST['pickuplocation'];
$destination = $_POST['destination'];

HTML on Google page:

</head>
<body onload="initialize()">
<div id="inputs">
  <pre class="prettyprint">
   </pre>
<form name="google" action="thirdform.php">
<table summary="google">


  <tr>
<td>&nbsp;</td>
<td><input name="Continue" value="Continue" type="submit" ></td>
<td>&nbsp;</td>
</tr> 

</table>
</form> 
</div>
<div id="outputDiv"></div>
<div id="map"></div>
</body>
</html>

I won't post the JavaScript of the Google Matrix other than the AJAX:

var distance = results[j].distance.text;
$.get("thirdform.php", {miles:distance} );

I'm not sure if the code above is correct, I'm guessing I'm going wrong somewhere, probably here. On the next page, (thirdform.php) PHP:

session_start();
$time = $_SESSION['time'];
$date = $_SESSION['date'];
$length = $_SESSION['length'];
$numberofpeople = $_SESSION['numberofpeople'];
$pickuplocation = $_SESSION['pickuplocation'];
$destination = $_SESSION['destination'];
$useofbus = $_SESSION['useofbus'];

var_dump($_SESSION);

echo "</br>";
$distance = $_GET['miles'];

echo "DISTANCE: " . $distance . "</br>";

I'm not able to get anything in the PHP variable $distance - it's empty. Am I coding incorrectly? I followed an example on-line from this website somewhere which claimed to work. I've read several articles and searched on Google and on this website but there doesn't seem to be a clear answer anywhere that isn't too complicated and relates to what I'm trying to do. I've read plenty of examples but they're all far too complicated for me to use and change to put into my code. There was some code I read where the page was sent straight to next page however I need to show the Google Map on my page and therefore need to use the button to move to the next page.

Could anyone give me a nudge in the right direction? Thanks.

JS:

<script>

  var map;
  var geocoder;
  var bounds = new google.maps.LatLngBounds();
  var markersArray = [];

  var origin = '<?php echo $pickuplocation; ?>';
  var destination = '<?php echo $destination; ?>';



  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(55.53, 9.4),
      zoom: 12,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('map'), opts);
    geocoder = new google.maps.Geocoder();
    calculateDistances()
  }

  function calculateDistances() {
    var service = new google.maps.DistanceMatrixService();
    service.getDistanceMatrix(
      {
        origins: [origin],
        destinations: [destination],
        travelMode: google.maps.TravelMode.DRIVING,
        unitSystem: google.maps.UnitSystem.IMPERIAL,
        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] + ' to ' + destinations[j]
              + ': ' + results[j].distance.text + ' in '
              + 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() {
    if (markersArray) {
      for (i in markersArray) {
        markersArray[i].setMap(null);
      }
      markersArray.length = 0;
    }
  }


  </script>

  <script type="text/javascript">

  var distance = results[j].distance.text;

  $('.button-class').click(function() { $.get("thirdform.php", {miles:distance},   function (data){alert(data)} ); });






</script>
12
  • 1. are you sure that distance is correct in the JS before you make the AJAX request? 2. In thirdform.php, what do you see when you print_r($_GET);? Commented Jan 28, 2013 at 19:03
  • Just to verify, are you reading the output of your PHP file from within your AJAX get request? What does $.get("thirdform.php", {miles:distance}, function(data){alert(data);}); give you? Commented Jan 28, 2013 at 19:04
  • in the javascript: outputDiv.innerHTML += origins[i] + ' to ' + destinations[j] + ': ' + results[j].distance.text + ' in ' + results[j].duration.text + '<br>'; so i assumed i could take results[j].distance.text and make that value a variable and that would work? Commented Jan 28, 2013 at 19:07
  • and i get literally nothing with print_r($_GET); Commented Jan 28, 2013 at 19:09
  • Just to verify, are you reading the output of your PHP file from within your AJAX get request? I'm not terribly sure what you mean by this, sorry Commented Jan 28, 2013 at 19:11

1 Answer 1

0

Since you are overriding the form action with the $.get, try removing the form and using a <button> instead of an <input> button.

Then have your ajax request run on that <button>.

Edit: It's also worth noting that you should probably just send data from the php file. You can then do any other manipulation("DISTANCE: ", "<br />") in the html/js.

5
  • i have no idea how to run the ajax request on a button though ;-; Commented Jan 28, 2013 at 19:49
  • $('.button-class').click(function() { // ajax here }); Commented Jan 28, 2013 at 19:55
  • so you're saying that all i need for the ajax on the google page is: var distance = results[j].distance.text; $('.button-class').click(function() { $.get("thirdform.php", {miles:distance} );}); and that should work? Commented Jan 28, 2013 at 20:04
  • Just to point out, you will still want to output the response from that call within the ajax call. otherwise you won't be able to see the response of the target PHP with the correct querystring. $('.button-class').click(function() { $.get("thirdform.php", {miles:distance}, function (data){alert(data)} ); }); Commented Jan 28, 2013 at 20:24
  • there appears to be no button. im no good at javascript and ive already done all manipulation with php then sent it to mysql which im not sure you can do with js? i also have limited time, only the rest of this week to finish the project. ;-; Commented Jan 28, 2013 at 20:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.