Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have an index.php that file contains php on top, then html and finally javascript. In my javascript part I get the values from my php part as follow:

var lati = <?php echo $valLat; ?>; var longi = <?php echo $valLong; ?>;

and I use the lati and longi to update a marker on a map.

How can I keep calling the php part of my code with javascript in order to get the most recent latitude and longitude without having to update the webpage?

Here is my current php code it works but I have to reload the whole page to get the new latitude and longitude.

`

/* This part will select GPS_data database and it will get the most recent latitude and longitude values
   these values are constantly updated in the database by a python file*/

//Selects GPS_data database.
mysql_select_db("GPS_data");

$sql = mysql_query("SELECT * FROM coordinates ORDER BY time DESC LIMIT 1"); //Gets the most recent lat and long.

$latitude = 'latitude';    //Set $latitude variable the same as the most recent latitude on the table.
$longitude = 'longitude';

$rows = mysql_fetch_assoc($sql);
$valLat = $rows['latitude'];
$valLong = $rows['longitude']; ?>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
114 views
Welcome To Ask or Share your Answers For Others

1 Answer

Minor changes to PHP file is required, plus some jQuery to retrieve lat/lon.

Changes:

  1. Added an array $data to PHP code.
  2. Stored lat and lon as elements of associated array to $data.
  3. Converted PHP array to object usig json_encode.
  4. Finally used echo, now $data will be available in jQuery as object.

Here is your modified PHP file.

<? 
// fetch_latlon.php

/* This part will select GPS_data database and it will get the most recent latitude and longitude values
   these values are constantly updated in the database by a python file*/

//Selects GPS_data database.
mysql_select_db("GPS_data");

$sql = mysql_query("SELECT * FROM coordinates ORDER BY time DESC LIMIT 1"); //Gets the most recent lat and long.

$latitude = 'latitude';    //Set $latitude variable the same as the most recent latitude on the table.
$longitude = 'longitude';

$rows = mysql_fetch_assoc($sql);
$valLat = $rows['latitude'];
$valLong = $rows['longitude']; 

// I have added this
$data = [
    'lat' => $valLat,
    'lon' => $valLong
];

echo json_encode($data);

?>

Then in your HTML add AJAX code.

<script>

function updateLatLon() {

    $.ajax({
        // name of file to call
        url: 'fetch_latlon.php',

        // method used to call server-side code, this could be GET or POST
        type: 'GET'

        // Optional - parameters to pass to server-side code
        data: {
            key1: 'value1',
            key2: 'value2',
            key3: 'value3'
        },

       // return type of response from server-side code
       dataType: "json"

        // executes when AJAX call succeeds
        success: function(data) {
            // fetch lat/lon
            var lat = data.lat;
            var lon = data.lon;

            // show lat/lon in HTML
            $('#lat').text(lat);
            $('#lon').text(lon);
        },

        // executes when AJAX call fails
        error: function() {
            // TODO: do error handling here
            console.log('An error has occurred while fetching lat/lon.');
        }
    });

}

// fetch lat/lon after each 3000 milliseconds
setTimeout(updateLatLon, 3000);

</script>

Side note: Convert your MySQL code to MySQLi because MySQL is deprecated.

For help in this conversion visit https://www.phpclasses.org/blog/package/9199/post/3-Smoothly-Migrate-your-PHP-Code-using-the-Old-MySQL-extension-to-MySQLi.html#convert


UPDATE

SOLVED Uncaught ReferenceError: $ is not defined

First you need to make sure that jQuery script is loaded. This could be from a CDN or local on your website. If you don't load this first before trying to use jQuery it will tell you that jQuery is not defined.

<script src="jquery.min.js"></script>

This could be in the HEAD or in the footer of the page, just make sure you load it before you try to call any other jQuery stuff.

Then you need to use one of the two solutions below

(function($){
// your standard jquery code goes here with $ prefix
// best used inside a page with inline code, 
// or outside the document ready, enter code here
 })(jQuery); 

or

jQuery(document).ready(function($){
// standard on load code goes here with $ prefix
// note: the $ is setup inside the anonymous function of the ready command
});

Please be aware that many times following code will not work, especially true in case of WordPress.

$(document).ready(function(){
    //code here
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...