Karthik Malla
Karthik Malla

Reputation: 5800

Passing values from JavaScript to PHP using AJAX

I don't know why my code is not working, I am trying to send the coordinates from JavaScript to PHP using AJAX and I am able to pull values from JavaScript to textbox but values are not passed to PHP. Any help is highly appreciated.

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    document.getElementById("getlat").value = position.coords.latitude;
    document.getElementById("getlon").value = position.coords.longitude;
}
$( document ).ready(function() {
$.ajax({url:"samepage3.php",type:"POST",async:false,
   data:{getlat:$("#getlat").val(),getlon:$("#getlon").val()}
});
});
</script>
</head>
<body onload="getLocation()">
<input type="text" id="getlat" name="getlat" /> 
<input type="text" id="getlon" name="getlon" />
<?php
if(isset($_POST["getlat"]))
{
    $lat = $_POST["getlat"];
    echo $lat;
}
if(isset($_POST["getlon"]))
{
    $lon = $_POST["getlon"];
    echo $lon;
}
?>
</body>
</html>

UPDATE 1:

I am running this code in file samepage3.php and I need the action to be happened on the same page without reloading the page

Upvotes: 0

Views: 980

Answers (4)

Chad Hedgcock
Chad Hedgcock

Reputation: 11755

The sole purpose of AJAX is to fetch and send data from a server without reloading the page.

You don't need any data from the server. You need data from the BROWSER--namely--geolocation coordinates, so AJAX and php have no bearing on what you need to do here. This can be done in pure HTML.

On the other hand, if you want to do something like save the coordinates to a database or use IP address as a fallback when the navigator doesn't support geolocation, that's when you could use the help of a server and AJAX would come into play.

Simply replace your ajax function with getLocation().

<!DOCTYPE html>
  <html>
    <head>
      <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
      <script>
        function getLocation() {
          if (navigator.geolocation) {
                 navigator.geolocation.getCurrentPosition(showPosition);
           }else{
             console.warn("Can't geolocate!");
             //this would be a good place to fall back on geolocation by IP (AJAX necessary)
           }
        }

        function showPosition(position) {
          console.info('Latitude: ' + position.coords.latitude);
          document.getElementById("getlat").value = position.coords.latitude;
          console.info('Longitude: ' + position.coords.longitude);
          document.getElementById("getlon").value = position.coords.longitude;
        }
        $( document ).ready(function() {
            getLocation();
        });
      </script>
   </head>
   <body>
     <input type="text" id="getlat" name="getlat" /> 
     <input type="text" id="getlon" name="getlon" />
   </body>
</html>

Upvotes: 0

Kevin
Kevin

Reputation: 41885

First off, separate the PHP processing. Now after getting the location using the callback then perform the AJAX. Sample Code:

samepage3.php

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}

function showPosition(position) {

    $("#getlat").val(position.coords.latitude);
    $("#getlon").val(position.coords.longitude);
    $.ajax({
        url: 'request.php',
        type: 'POST',
        dataType: 'JSON',
        data:{
            getlat: $("#getlat").val(),
            getlon: $("#getlon").val()
        },
        success: function(response) {
            console.log(response);
        }
    });
}

$(document).ready(function() {
    getLocation();
});
</script>
<body>
<input type="text" id="getlat" name="getlat" />
<input type="text" id="getlon" name="getlon" />

request.php

<?php
if($_SERVER['REQUEST_METHOD'] == 'POST') {
    $lat = $_POST["getlat"];
    $lon = $_POST["getlon"];
    echo json_encode(array('lat' => $lat, 'lon' => $lon));
    exit;
}
?>

Upvotes: 0

Ford
Ford

Reputation: 31

The root cause is getLocation function will be a big delay, so you need to fire ajax call after getLocation is done. Please see the blow revised version:

<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
}
function showPosition(position) {
    document.getElementById("getlat").value = position.coords.latitude;
    document.getElementById("getlon").value = position.coords.longitude;
    $.ajax({url:"samepage3.php",type:"POST",async:false,
           data:{getlat:$("#getlat").val(),getlon:$("#getlon").val()}
        });
}
$( document ).ready(function() {

});
</script>
</head>
<body onload="getLocation()">
<input type="text" id="getlat" name="getlat" /> 
<input type="text" id="getlon" name="getlon" />
<?php
if(isset($_POST["getlat"]))
{
    $lat = $_POST["getlat"];
    echo $lat;
}
if(isset($_POST["getlon"]))
{
    $lon = $_POST["getlon"];
    echo $lon;
}
?>
</body>
</html> 

The only change is doing ajax call in the function showPosition.

Upvotes: 0

Prabowo Murti
Prabowo Murti

Reputation: 1341

You can not execute the PHP script on the samepage3.php, after the page is fully loaded. I suggest to separate the page, and create the response using AJAX. Something like this.

File index.php

<!DOCTYPE html>
<html>
    <head>
        <script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.min.js"></script>
        <script>
            function getLocation() {
                if (navigator.geolocation) {
                    navigator.geolocation.getCurrentPosition(showPosition);
                }

            }
            function showPosition(position) {
                document.getElementById("getlat").value = position.coords.latitude;
                document.getElementById("getlon").value = position.coords.longitude;
            }

            function fireAjax(){
                $.ajax({url:"response.php",type:"POST",async:false,
                    data:{getlat:$("#getlat").val(),getlon:$("#getlon").val()},
                    success: function (response){
                        $('#response').html(response);
                    }
                });
            }
        </script>
    </head>
    <body onload="getLocation()">
        <input type="text" id="getlat" name="getlat" /> 
        <input type="text" id="getlon" name="getlon" />

        <button onclick="fireAjax()" >Send</button>

        <div id="response">
        </div>
    </body>
</html>

File response.php

<?php
if (isset($_POST["getlat"]))
{
    $lat = $_POST["getlat"];
    echo 'Latitude: ', $lat, '<br/>';
}
if (isset($_POST["getlon"]))
{
    $lon = $_POST["getlon"];
    echo 'Longitude : ', $lon;
}

Upvotes: 1

Related Questions