0

I am new to AJAX and JavaScript so please forgive me if I am acting stupid but I am trying to pass the variable routeMid to the php page processing.php(preferable automatically one routeMid has been calculated) I tried out this code but it breaks the entire webpage. I attached the snippet with the ajax part I am having trouble with and the php code on the next page so any help would be greatly appreciated. Thanks again in advance!

<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false">

</script>
<script type ="text/javascript" src="http://www.geocodezip.com/scripts/v3_epoly.js"></script>
<script type="text/javascript">
  var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;
  var polyline = null;
  var infowindow = new google.maps.InfoWindow();
  var addresses = <?php echo json_encode($addresses); ?>;

function createMarker(latlng, label, html) {
    var contentString = '<b>'+label+'</b><br>'+html;
    var marker = new google.maps.Marker({
        position: latlng,
        map: map,
        title: label,
        zIndex: Math.round(latlng.lat()*-100000)<<5
        });
        marker.myname = label;

    google.maps.event.addListener(marker, 'click', function() {
        infowindow.setContent(contentString+"<br>"+marker.getPosition().toUrlValue(6)); 
        infowindow.open(map,marker);
        });
    return marker;
}

  function initialize() {
    directionsDisplay = new google.maps.DirectionsRenderer({suppressMarkers:true});
    var chicago = new google.maps.LatLng(41.850033, -87.6500523);
    var myOptions = {
      zoom: 6,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: chicago
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    polyline = new google.maps.Polyline({
    path: [],
    strokeColor: '#FF0000',
    strokeWeight: 3
    });
    directionsDisplay.setMap(map);
    calcRoute();
  }

  function calcRoute() {
    var start = addresses[0];
    var end = addresses[1];
    var travelMode = google.maps.DirectionsTravelMode.DRIVING

    var request = {
        origin: start,
        destination: end,
        travelMode: travelMode
    };
    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        polyline.setPath([]);
        var bounds = new google.maps.LatLngBounds();
        startLocation = new Object();
        endLocation = new Object();
        directionsDisplay.setDirections(response);
        var route = response.routes[0];
        var summaryPanel = document.getElementById("directions_panel");
        summaryPanel.innerHTML = "";

        // For each route, display summary information.
    var path = response.routes[0].overview_path;
    var legs = response.routes[0].legs;
        for (i=0;i<legs.length;i++) {
          if (i == 0) { 
            startLocation.latlng = legs[i].start_location;
            startLocation.address = legs[i].start_address;
            marker = createMarker(legs[i].start_location,"midpoint","","green");
          }
          endLocation.latlng = legs[i].end_location;
          endLocation.address = legs[i].end_address;
          var steps = legs[i].steps;
          for (j=0;j<steps.length;j++) {
            var nextSegment = steps[j].path;
            for (k=0;k<nextSegment.length;k++) {
              polyline.getPath().push(nextSegment[k]);
              bounds.extend(nextSegment[k]);
            }
          }
        }

        polyline.setMap(map);

        computeTotalDistance(response);
      } else {
        alert("directions response "+status);
      }
    });
  }

var totalDist = 0;
var totalTime = 0;

      function computeTotalDistance(result) {
      totalDist = 0;
      totalTime = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) {
        totalDist += myroute.legs[i].distance.value;
        totalTime += myroute.legs[i].duration.value;      
      }
      putMarkerOnRoute(50);
      var routeMid = putMarkerOnRoute(50);
      document.getElementById("hiddenVal").value = routeMid;


            $(".clickable").click(function() {
                //alert($(this).attr('id'));
                $.ajax({
                    type: "POST",
                    url: 'processing.php',
                    data: { value : routeMid }
                });
            });
        });


      totalDist = totalDist / 1000.
      }

      function putMarkerOnRoute(percentage) {
        var distance = (percentage/100) * totalDist;
        var time = ((percentage/100) * totalTime/60).toFixed(2);
        var routeMidpoint;
        if (!marker) {
          marker = createMarker(polyline.GetPointAtDistance(distance),"time: "+time,"marker");
          routeMidpoint = polyline.GetPointAtDistance(distance);
        } else {
          marker.setPosition(polyline.GetPointAtDistance(distance));
          marker.setTitle("time:"+time);
          routeMidpoint = polyline.GetPointAtDistance(distance);
        }
        return routeMidpoint;
      }
</script>

processing.php

<?php
echo $_POST["value"];
?>
1
  • Your document ready function should exist outside of your cmoputeTotalDistance function call. In fact, you should probably have all of your computeTotalDistance logic inside that click handler function, though it is not clear where your result value comes from. Commented Apr 22, 2014 at 23:48

1 Answer 1

1

I think this is what you are trying to accomplish:

$(document).ready(function() {

function computeTotalDistance() {
      totalDist = 0;
      totalTime = 0;
      var myroute = result.routes[0];
      for (i = 0; i < myroute.legs.length; i++) {
        totalDist += myroute.legs[i].distance.value;
        totalTime += myroute.legs[i].duration.value;      
      }
      putMarkerOnRoute(50);
      var routeMid = putMarkerOnRoute(50);
      document.getElementById("hiddenVal").value = routeMid;

      $.ajax({
         type: "POST",
         url: 'processing.php',
         data: { value : routeMid },
         success:function(result){
            alert("returned from php page: " + result);
         }
      });

      totalDist = totalDist / 1000.


       }

});

And then you can do what you want with the ajax result. I'm not sure what you are trying to accomplish with the click(). If you are trying to call the above function then this will work:

$(".clickable").click(function() {
 computeTotalDistance();
});
Sign up to request clarification or add additional context in comments.

4 Comments

I edited the code to reflect the entire JavaScript section of the page. I tried this solution out but it didn't work. Your help is greatly appreciated!
take your click function out of your computetotaldistance function. There is no good reason to have it in there. You also aren't doing anything with your ajax result. See the success option of my ajax function.
Thanks for your help. So I took the click function out, but should the $(document).ready(function() { encapsulate the entire javascript code or just the computetotaldistance function? Thanks again for your help!
$(document).ready() can encapsulate all your javascript, within script tags, but you should know what it does. It basically just waits until the document (DOM) has completely loaded until loading your js so for functions that manipulate the DOM it is necessary

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.