-1

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']; ?>

2 Answers2

1

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
});
Hamza Rashid
  • 1,329
  • 15
  • 22
  • Oh my god it became clearer! Now I understand !!!!! :D THANK YOU I really appreciate your time to help me! Have a good one Hamza! – Juan Jose Jaramillo Apr 11 '17 at 23:44
  • pleasure. happy coding! :) – Hamza Rashid Apr 11 '17 at 23:52
  • I just solved it dear Hamza well I think. However I am getting this one: Uncaught ReferenceError: $ is not defined at the end of this line $.ajax({ – Juan Jose Jaramillo Apr 12 '17 at 00:58
  • I just solved it dear Hamza well I think. However I am getting this one: Uncaught ReferenceError: $ is not defined at the end of this line $.ajax({. It is weird as when i place: before my own script I don't get the Uncaught ReferenceError: $ is not defined. But I get the Uncaught ReferenceError: lati is not defined. – Juan Jose Jaramillo Apr 12 '17 at 01:07
  • You reference to `jquery.js` file will always come before any usage of `jQuery` in HTML code. – Hamza Rashid Apr 12 '17 at 01:23
  • Ok yes, I currently have it before. Do you want me to share my webpage with you using a tunnel maybe you could help me to find the error. It seems like the ajax call is not able to get the values of lati and longi. – Juan Jose Jaramillo Apr 12 '17 at 01:25
  • try putting everything `jQuery` inside `$(document).ready(function () { //your code here });` – Hamza Rashid Apr 12 '17 at 01:28
  • Thank you for your help! Yes I don't have that error anymore. I just have the (index):84 Uncaught ReferenceError: lati is not defined I guess it is like lati has not been declared so it is unable to use it. However I don't understand as it is clearly var lati = data.lat; inside the Ajax call – Juan Jose Jaramillo Apr 12 '17 at 01:41
  • it's time to start debugging your `JS`. The easiest method is to use `console.log(lati)` inside `success` function to see if `lati` variable exists and what's its value? – Hamza Rashid Apr 12 '17 at 01:44
  • It says undefined – Juan Jose Jaramillo Apr 12 '17 at 01:46
  • do this `console.log(data);` also inside `success` function – Hamza Rashid Apr 12 '17 at 01:48
  • I get my coordinated correctly like this: Object {lat: "myLat", lon: "myLong"} – Juan Jose Jaramillo Apr 12 '17 at 01:51
  • Ok I now get the console to correctly print my latitude. I placed it before var lati = data.lat; that is why I got undefined sorry for that error. However I still get the same error. The first time it is reported it is in the following line: var myLatLng = {lat: lati, lng: longi}; When I try to also console.log(lati); but outside the ajax it does not print to the console is it normal? I also saw this in another stackoverflow question: AJAX is asynchronous, you cannot return anything from it. You should consume the results of an AJAX request only inside the success callback: – Juan Jose Jaramillo Apr 12 '17 at 01:55
  • please share your `JS` code inside `success` function by sharing it online like on https://jsfiddle.net/ – Hamza Rashid Apr 12 '17 at 01:58
  • **Idea** try creating a variable outside before `$.ajax` like `var myLatLon = {};`. Then inside `success` function assign it value of `data` like `var myLatLon = data;`. Then you can use `myLatLon` outside `$.ajax` call. – Hamza Rashid Apr 12 '17 at 02:01
  • Ok, it worked. Now there is a new problem tho haha sorry. Do you think that by using jquery and ajax it might give a problem to the webpage to load? My google map loads correctly on the computer but when I try to load it on a mobile device it stays grey for 98% of the time. This is weird I thought that maybe some part of the code gets loaded too fast or does not have time to load properly but I don't know really. I removed the ajax/jquery part of the code I added and it works all the time. It seems it is that part of code. Have you had any similar problems? Thank you. – Juan Jose Jaramillo Apr 12 '17 at 06:15
0

You can use setTimeout javascript function in your code and use an ajax call to reload the variables you need. for example you can use jQuery get function to execute an ajax call.

Alireza Zojaji
  • 802
  • 2
  • 13
  • 33
  • Yes I use setInterval. I am trying to figure out how to run the whole php code and then pass the latitude and longitude variables to javascrit – Juan Jose Jaramillo Apr 11 '17 at 21:54
  • @JuanJoseJaramillo Just use `$_GET` statements to return the only variable you need for one single action in a separate PHP document. That way it's easier to use AJAX to gather one single variable. –  Apr 11 '17 at 21:58
  • oh ok, i call the other file with ajax and the i get that variable. thanks man I think I know now – Juan Jose Jaramillo Apr 11 '17 at 22:00
  • @JuanJoseJaramillo Your PHP file may look like this: https://pastebin.com/HTZ7ELaq –  Apr 11 '17 at 22:01