2

I need to get the distance between two points from JavaScript to PHP using Google Maps. Below is my function to get the distance and post no problems. Now, how can I send the arrays (i.e. volunteerDist and tvid) to another php file (i.e. distanceToDb.php) and what should be the code of my distanceToDb.php to get these data? Thanks! Actual codes is highly appreciated.

<?php
    function getFDistance(lat, lng, vlat, vlng, vid) {
        var eventlocation = new GLatLng(lat, lng);
        var volunteerDist = new Array();
        var tvid          = new Array();
        var volunteerlocation;

        for(i=0;i<lat.length;i++) {
            tvid[i] = vid[i];
            volunteerlocation = new GLatLng(vlat[i], vlng[i]);
            volunteerDist[i] = (Math.round((eventlocation.distanceFrom(volunteerlocation) / 1000)*10)/10);
        }
        $.ajax({
            type: 'POST',
            url: "distanceToDb.php",
            data: {tvid: tvid, volunteerDist: volunteerDist},
            success: function(data){
                alert("Successful");
            },
            dataType: "json"
        });
    }
?>
1
  • something's bugging me there... you have JS code inside PHP tags ? Commented Mar 15, 2012 at 11:43

1 Answer 1

1

I've passed arrays and objects using JSON in javascript, let's say through a jquery.post call:

$.ajax({
    type: 'POST',
    url: "distanceToDb.php",
    data: {tvid: tvid, volunteerDist: volunteerDist},
    success: successfunction,
    dataType: "json"

});

Then, in the php file you just do this:

$js_data_arr = json_decode($_POST['data']);
Sign up to request clarification or add additional context in comments.

14 Comments

in my code's case, what specific line should I add? do i still need the location.href?
Nope, actually instead of the location.href line, you would call the jquery.post (sorry for assuming you're using jQuery).
I updated my answer, so it's clearer. Let me know if you have any issue.
what should url and data contain? please use my existing variables based on the given example to make things clear.. thanks.. i am new to this
and by the way, I need to pass two arrays here
|

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.