Skip to content Skip to sidebar Skip to footer

Send JavaScript Variable To PHP

What im trying to do here is sending a JavaScript variable to a PHP function. What I'm developing is a jQuery Mobile App where you can check in when you reach a specific longitude/

Solution 1:

You're sending the request before you get the geolocation response

You need to do it inside the callback.


Solution 2:

Try to use AJAX

http://api.jquery.com/jQuery.ajax/

Your handler should look like this:

$.ajax({
  type: "POST",
  url: "checklocation.php",
  data: "lat="+latitude+"&longi="+longitude
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});

Solution 3:

navigator.geolocation.getCurrentPosition(function(position) {
                var latitude = position.coords.latitude;
                var longitude = position.coords.longitude;
                document.write("lat", latitude);
                document.write('<br /><br />');
                document.write("long", longitude);
            });

you have local vars latitude and longitude here. If you want to use them outside of this function you can use global vars:

var latitude;
var longitude;
//...
navigator.geolocation.getCurrentPosition(function(position) {
                latitude = position.coords.latitude;
                vlongitude = position.coords.longitude;
                document.write("lat", latitude);
                document.write('<br /><br />');
                document.write("long", longitude);
            });

//usage(transfer) of vars

Solution 4:

Try to use the AJAX-Request in callback (Proof of concept, not shure if it works):

function testResults()
{
    if (navigator.geolocation)
    {
        //Get the current position
        navigator.geolocation.getCurrentPosition(function (position)
        {
            var latitude = position.coords.latitude;
            var longitude = position.coords.longitude;

            // do callback                
            $.ajax(
            {
                type: "POST",
                url: "checklocation.php",
                data: "lat=" + latitude + "&lon=" + longitude
            }).done(function (msg)
            {
                alert("Data Saved: " + msg);
            });

        });
    }
    else
    {
        alert("Sorry... your browser does not support the HTML5 GeoLocation API");
    }
}

testResults();

Cheers. Frank


Post a Comment for "Send JavaScript Variable To PHP"