Passing values from JavaScript to PHP using AJAX

前端 未结 4 1387
小鲜肉
小鲜肉 2020-12-22 07:12

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 v

相关标签:
4条回答
  • 2020-12-22 07:25

    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;
    }
    ?>
    
    0 讨论(0)
  • 2020-12-22 07:28

    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;
    }
    
    0 讨论(0)
  • 2020-12-22 07:31

    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>
    
    0 讨论(0)
  • 2020-12-22 07:37

    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.

    0 讨论(0)
提交回复
热议问题