0

I have a problem with passing Javascript calculation (distance and travel time from google) to form as hidden input. Using onSubmit so i can use it on the next page). Specifilcy (mi and time_teken). Displaying this values with inner html on the same page there is no problem at all. And all work just fine. As you can see im also passing lon and lat values using similar script (which is not here to make a submited code shorter, Also Work with no problem. But for these valus i use on change method. I tried a lot of different methods but at this point im totaly lost.

I will appraciate some help.

Thank you very much in advance.

    <script language="javascript" type="text/javascript">window.onload=function(){initialize(51.508515, -0.12548719999995228);}</script>

<input type="hidden" value="1.5" id="more_then" name="more_then"/>
<input type="hidden" value="0" id="less_then" />
<script language="javascript">
 function get_distance(form){
     from = form.postcode1.value;
     to = form.postcode2.value;
     calcRoute(from,to);

 }
</script>

<form id="booking" name="booking"  action="test5.php" method='post' onsubmit='get_distance(this.form);'>
<input type="text" name="postcode1" id="postcode1" class="input-postcode1" onChange="Geocode1()" placeholder='Postcode or Town' /></td>
<input type="text" name="postcode2" id="postcode2" class="input-postcode1" onChange="Geocode2()" placeholder='Postcode or Town'/></td>
 <input name="lat1" type="hidden" id="lat1">
<input name="lon1" type="hidden" id="lon1">
 <input name="lat2" type="hidden" id="lat2">
<input name="lon2" type="hidden" id="lon2">
<input name="distance2" type="hidden" id="distance2">
<input name="timetaken" type="hidden" id="timetaken">
<input type="hidden" value="7" name="map_zoom" id="map_zoom"/>
<input type="hidden" value="£" id="curr_format"/>
<input type='submit' name='submit' id='submit' value='Calculate' class='LMV-callback'  >
</form>


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

<script type="text/javascript">
var directionDisplay;
  var directionsService = new google.maps.DirectionsService();
  var map;
  function initialize(lat,lng) {
    directionsDisplay = new google.maps.DirectionsRenderer();
    //var location = new google.maps.LatLng(9.93123, 76.26730);
    var location = new google.maps.LatLng(lat, lng);
    var zm =  parseInt(document.getElementById('map_zoom').value);
    var myOptions = {
      zoom: zm,
      mapTypeId: google.maps.MapTypeId.ROADMAP,
      center: location
    }
    map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    directionsDisplay.setMap(map);

}

  function calcRoute(from,to){
    var start = from;
    var end = to;
    var request = {
        origin:start,
        destination:end,
        travelMode: google.maps.DirectionsTravelMode.DRIVING,
        unitSystem: google.maps.DirectionsUnitSystem.METRIC     //IMPERIAL     //METRIC
    };
    // function to round the decimal digits eg: round(123.456,2); gives 123.45
    function round(number,X) {
        X = (!X ? 2 : X);
        return Math.round(number*Math.pow(10,X))/Math.pow(10,X);
    }

    directionsService.route(request, function(response, status) {
      if (status == google.maps.DirectionsStatus.OK) {
        directionsDisplay.setDirections(response);

        var distance = response.routes[0].legs[0].distance.text;
        var time_taken = response.routes[0].legs[0].duration.text;
        var calc_distance = response.routes[0].legs[0].distance.value;
        var less_then =  document.getElementById('less_then').value;
        var more_then =  document.getElementById('more_then').value;
        var curr_format =  document.getElementById('curr_format').value;

                if (calc_distance <= 16510) {
                    var amount_to_pay = calc_distance * less_then;
                }
                else {
                    var amount_to_pay = (calc_distance-16510) * more_then;
                }

    function roundNumber(numbr,decimalPlaces) 
    {
        var placeSetter = Math.pow(10, decimalPlaces);
        numbr = Math.round(numbr * placeSetter) / placeSetter;
        return numbr;
    }
    var mi =  calc_distance / 1.609;
    var mi = mi/1000;
    var mi = roundNumber(mi, 2);   //Sets value to 2 decimal places.

/// my problem might by here

    document.getElementById("distance2").value = mi;
    $("#distance2").val(mi);
    document.getElementById("timetaken").value = time_taken;
    $("#timetaken").val(time_taken);



                var rounded_amount_to_pay = round(amount_to_pay/1000,2); 

        document.getElementById('distance').innerHTML = '<div class="distance-inner"><span>'+ "The distance between <em>"+from+"</em> and <em>"+to+"</em>: <strong> "+mi+ " mi</strong>\n\
                <br/>\n\
                Time take to travel: <strong>"+time_taken+"</strong><br/>\n\
                </span></div>";

            var steps = "<ul>";
        var myRoute = response.routes[0].legs[0];
        for (var i = 0; i < myRoute.steps.length; i++) {
         steps += "<li>" + myRoute.steps[i].instructions + "</li>";
        }
        steps += "</ul>";
        document.getElementById('steps').innerHTML = '<div class="steps-inner"><h2>Driving directions to '+response.routes[0].legs[0].end_address+'</h2>'+steps+'</div>';
      }
      else{
        document.getElementById('distance').innerHTML = '<span class="gdc-error">Google Map could not be created for the entered parameters. Please be specific while providing the destination location.</span>';
      }
    });

  }

//window.onload=function(){initialize();}// JavaScript Document

</script>
Nita
  • 561
  • 5
  • 28

3 Answers3

0

What seems to be happening is you have an action="test5.php" on the same form where you are doing the submit on and trying to listen for the events. Since getting the route data is an asynchronous process meaning it can return a value at any indiscriminate time in the future, you aren't getting the values immediately. They are only being set once directionsService.route(request, function(response, status) {... returns and your inline anonymous function function(response, status){... runs. By this point your form will have submitted itself to the test5.php page and thus your values are empty.

The other values you say you are setting successfully after change event are immediate and hence get included in the form before you submit it.

What I would suggest is to either use AJAX to submit the form or add a check to see if the form has been submitted before and if not, prevent a submit via javascript return false JavaScript code to stop form submission and then also when you have returned the values from your call to googles API you can force another submission via javascript but this time return true if you have verified that the data is in the hidden inputs.

Community
  • 1
  • 1
Rob Schmuecker
  • 8,934
  • 2
  • 18
  • 34
0
document.booking.elements['distance'].value = mi;
document.booking.elements['timetaken'].value = time_taken;
Nita
  • 561
  • 5
  • 28
-1

Try this:

var lat = document.getElementById("lat1").value;

or

var lat = document.booking.elements['lat1'].value;
Sunil B N
  • 4,159
  • 1
  • 31
  • 52
  • i do not have problem with passing lat1, lon1 or lat2, lat1 but i will try with var lat = document.booking.elements['lat1'].value; – Nita Jul 22 '14 at 15:02
  • what im trying to do is to pass ( var mi = roundNumber(mi, 2); document.getElementById("distance2").value = mi;) to with onsubmit='get_distance(this.form);'> – Nita Jul 22 '14 at 15:04
  • Soryy i haven't see your advice Rob. well i kind of find a solution for my problem,but it's not close to be perfect, works but still would like to find a better way.( onChange="Geocode1(); get_distance(this.form);" - onChange="Geocode2(); get_distance(this.form);") You recommended AJAX. How that could be done. I dont have much experience with AJAX at all. Some example will help me a lot. Thx in advance. – Nita Jul 22 '14 at 15:47