简体   繁体   中英

I am using Jquery to load dynamic php data into my file but cannot store the data into Javascript variables

In my 'retrievedata.php' file, I am printing out dynamically updated latitude and longitude paragraphs. This is working fine:

<html>
  <body>
    <p id="userlatlng"> {lat: <?php echo $lat ?>, lng: <?php echo $lng ?> } </p>
  </body>
</html>

In my other file to plot these points on Google Maps, I am struggling to store the data from the 'retrievedata.php' file into Javascript variables. Javascript won't let me getElementByID in this case and I don't know how to resolve this.

   <html>
  <head>
    <link href="style.css" rel="stylesheet" type="text/css"></link>
    <link rel="icon" href="images/favicon.png">
    <script src="https://www.google.com/recaptcha/api.js" async defer></script>
  </head>
  <body>
    <div id="map"></div>
    <input type="button" id="display" value="Display All Data" />
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script>

      $(document).ready(function() {
        $(function retrieveData(){
        $.ajax({    //create an ajax request to display.php
          type: "GET",
          url: "retrievedata.php",
          dataType: "html",   //expect html to be returned
          success: function(response){
              $("#responsecontainer").html(response);
          }
          });
          timerId = setTimeout(retrieveData, 1000);
        });
      });

      </script>

      <p id="responsecontainer"></p>
      <h2 id="userlatlngtest">test</h2>

      <script>
      var response = document.getElementById("responsecontainer").innerHTML;

      function initMap() {
          var leeds = {lat: 53.807081, lng: -1.555848};
          map = new google.maps.Map(document.getElementById('map'), {
              center: leeds,
              zoom: 16
          });

          var marker = new google.maps.Marker({
                    position: userlat,
                    map: map,
                  });

      }

    </script>
    <script async defer
    src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXB2UeKrP80RfU-webxxV757b3j9vubcc&callback=initMap">
    </script>

  </body>
</html>

Send json output and parse it in the ajax call

<?php
header( 'Content-Type: application/json' );
echo json_encode(array('lat'=> $lat, 'lng'=> $lng));

Then your html becomes

<html>
    <head>
        <link href="style.css" rel="stylesheet" type="text/css"></link>
        <link rel="icon" href="images/favicon.png">
        <script src="https://www.google.com/recaptcha/api.js" async defer></script>
    </head>
    <body>
        <div id="map"></div>
        <input type="button" id="display" value="Display All Data" />
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

        <h2 id="userlatlngtest">test</h2>


        <script>
            function initMap() {
                var leeds = {lat: 53.807081, lng: -1.555848};
                var map, marker;
                map = new google.maps.Map(document.getElementById('map'), {
                    center: leeds,
                    zoom: 16
                });
                $.ajax({
                    type: "GET",
                    url: "retrievedata.php",
                    success: function (response) {
                        marker = new google.maps.Marker({
                            position: response,
                            map: map,
                        });
                    }
                });
            }
        </script>
        <script async defer src="https://maps.googleapis.com/maps/api/js?key=AIzaSyCXB2UeKrP80RfU-webxxV757b3j9vubcc&callback=initMap">
        </script>

    </body>
</html>

I have got it working. There were a number of problems, including that I had HTML in my db_connect.php file.

Here is the working php code:

<?php
/*
  require_once("db_connect.php");
*/
  $db_hostname = 'xxxxxxxxx';
    $db_database = 'xxxxxxxx'; //'Your database name'
    $db_username = 'xxxxxxxxxx'; //'username';
    $db_password = 'xxxxxxxxxx'; //'password';
    $db_status = 'not initialised';
    $db_server = mysqli_connect($db_hostname, $db_username, $db_password);
    $db_status = "connected";

    if (!$db_server){
        die("Unable to connect to MySQL: " . mysqli_connect_error());
        $db_status = "not connected";
    }


  mysqli_select_db($db_server, $db_database) or die("Couldn't find db");
  $query = "SELECT * FROM locations WHERE ID = 1";
  $result = mysqli_query($db_server, $query);
  if(!$result) die('Query failed: ' . mysqli_error($db_server));

  $str_result = mysqli_num_rows($result). "rows<br />";
  while($row = mysqli_fetch_array($result)){
    $lat = $row['lat'] ;
    $lng = $row['lng'] ;
  }


 echo $lat . "," .  $lng ?>

And in the file to plot the location point:

<!DOCTYPE html>
<html>
<head>
    <title>Location tracking Google map</title>
</head>
<body>
    <h1>Location tracking Google Map</h1>

    <!-- testing, next 3 lines can be removed -->
    <h4>Testing variables (these latlngs have no effect on the map):</h4>
    <p id="responsecontainer"></p>
    <p id="responsecheck"></p>

    <!-- the map -->
    <div id="map" style="width:600px;height:400px">My map will go here</div>

</body>
</html>

<!-- the scripts -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
    //Global variables for map and marker
    var map;
    var marker;
    //function to set uo the map
    function myMap() {
        var mapOptions = {
            center: new google.maps.LatLng(51.5, -0.12),
            zoom: 10,
            mapTypeId: google.maps.MapTypeId.HYBRID
        }
        map = new google.maps.Map(document.getElementById("map"), mapOptions);
        marker = new google.maps.Marker({
            position: new google.maps.LatLng(51.5, -0.12),
            map: map,
            title: 'Initial marker!'
          });
    }
    //jQuery and ajax call to get new location location
    $(document).ready(function() {
        $(function retrieveData(){
           $.ajax({    //create an ajax request to display.php
              type: "GET",
              url: "retrievedata.php",
              dataType: "html",   //expect html to be returned
              success: function(response){

                  var res = response.split(",");
                  myLat = res[0];
                  myLng = res[1];
                  point = new google.maps.LatLng(myLat, myLng);
                  map.setCenter(point);
                  changeMarkerPosition(marker, point);

                  //testing - next two lines can be removed
                  $("#responsecontainer").html(response);
                  $("#responsecheck").html("myLat: " + myLat + ", myLng: " + myLng);
              }
          });
          timerId = setTimeout(retrieveData, 1000);
        });
    });
    //function to update marker location on map
    function changeMarkerPosition(mymarker, location){
        mymarker.setPosition(location);
    }
</script>
<script src="https://maps.googleapis.com/maps/api/js?key=AIsCXBsss2UeKrP80RfU-webxxV757b3j9vubcc&callback=myMap"></script>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM