Refresh Table Only PHP - javascript

So this page is reloding the location from the database.(This part is working).
But my table is not refreshing no matter what i do.I don't want to refresh the whole page onle the table itself
I just Want to refresh the table in some x time but everthing i do it's not working ,i tried so many times but i can't figure it out.
<?php
$id = (isset($_GET['id'])) ? ((int) $_GET['id']) : 0; // if we got input from user convert to numbers else set to 0
if($id <= 0) // the number must be greater than 0
exit();
require_once("db.php"); // connect to the database
?>
<!DOCTYPE html>
<html>
<head>
<title>Hello User</title>
<meta charset="UTF-8">
<script async defer src="https://maps.googleapis.com/maps/api/js?language=iw&region=IL&key=AIzaSyDyXdL4cZlxo3ldIuvi6_HpZa2jhj7iOU0&callback=initialize"
type="text/javascript"></script>
<style>#map { height: 600px; width: 1500px}</style>
<script>
$(document).ready(function(){
refreshTable();
});
function refreshTable(){
$('#tablediv').load('googlemaps.php');
setInterval(refreshTable, 1000);
}
</script>
</script>
</head>
<body>
<h1>Tracking Program</h1>
<div id="map"></div> <!-- map div !-->
<div id="tablediv">
<table style="background-color: red;" id="tableid" >
<thead>
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Id</th>
<th>Phone Number</th>
<th>Address</th>
</tr>
</thead>
<tbody>
<?php
// get all data from the table and print it
if($result = $db->query("SELECT FirstName, Lastname, Id, Phone,Address FROM details WHERE RowNum ORDER BY RowNum DESC LIMIT 1")) {
while($row = $result->fetch_assoc()) {
?>
<tr>
<td><?=$row['FirstName']; ?></td>
<td><?=$row['Lastname']; ?></td>
<td><?=$row['Id']; ?></td>
<td><?=$row['Phone']; ?></td>
<td><?=$row['Address']; ?></td>
</tr>
<?php
}
$result->close(); //free the result
}
?>
</tbody>
</table>
</div>
</body>
<script type="text/javascript">
var marker, map; // make them global to get access from other functions
function initialize(myLatlng) {
myLatlng = myLatlng || "<?php include("lastloc.php"); ?>";
myLatlng = myLatlng.split(",");
myLatlng = new google.maps.LatLng(myLatlng[0], myLatlng[1]);
var mapOptions = {
zoom: 11,
center: myLatlng
}
map = new google.maps.Map(document.getElementById('map'), mapOptions);
marker = new google.maps.Marker({
position: myLatlng,
map: map,
title: 'מיקום אחרון'
});
}
// ajax request to load last location
function lastLocation(){
var xmlhttp;
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function(){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200){
// method 1
//initialize(xmlhttp.responseText);
// method 2
myLatlng = xmlhttp.responseText.split(",");
myLatlng = new google.maps.LatLng(myLatlng[0], myLatlng[1]);
marker.setPosition(myLatlng); // update the position of the marker on the map
map.setCenter(myLatlng); // update the center of the map
}
}
xmlhttp.open("GET", "lastloc.php?id=<?=$id; ?>", true);
xmlhttp.send();
}
// timer to refresh the last location we have in the database
setInterval(lastLocation, 5000);
</script>
</html>
<?php
// close the connection to the datebase
if($db)
$db->close();
?>

Related

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>

Loading latitude/longitude from MySQL database and showing point on Google Maps using PHP,html and JavaScript

I googled a lot but all the solutions i found didn't work for me (even google maps tutorial). I have a MySQL database where I store latitude and longitude values in Float type columns. I wrote php script which connects to the database and selects those values. The idea is that php script passes an array of longitude and latitude values to JavaScript and then Javascript iterate on that array making new markers on Google Maps. Here is my actual code:
<html>
<head>
<style>
#map {
width: 100%;
height: 700px;
background-color: grey;
}
</style>
</head>
<body>
<?php
$query ="SELECT latitude,longitude FROM markers";
$result_array=Array();
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$latitude=$row['latitude'];
$longitude=$row['longitude'];
$result_array[]=array('latitude'=>$latitude,'longitude'=>$longitude);
}
$json=json_encode($result_array);
$con->close();
?>
<h3>MyMap</h3>
<div id="map"></div>
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 41.5400 , lng: 12.2500},
zoom: 6
});
var array="<?php echo $json_array;?>";
for(var i=0;i<array.length;i++){
var myLatLng=new google.maps.LatLng(lat,lon);
var marker=new google.maps.Marker({
map:map,
position: myLatLng,
});
//}
}
</script>
<script async defer
src=MY GOOGLE API MAP>
</script>
</body>
</html>
Can anyone help me or suggest other ways to do the same thing?
Try putting newlines between <?php and the actual content, like so:
var array=JSON.parse("<?php
echo $json_array;
?>");
The PHP substitution should put the double quotes on the same line.
<html>
<head>
<style>
#map {
width: 100%;
height: 700px;
background-color: grey;
}
</style>
</head>
<body>
<?php
$query ="SELECT latitude,longitude FROM markers";
$result_array=Array();
$con = new mysqli($host, $user, $password, $dbname, $port)
or die ('Could not connect to the database server' . mysqli_connect_error());
$result = mysqli_query($con,$query);
while($row = mysqli_fetch_array($result,MYSQLI_ASSOC)){
$latitude=$row['latitude'];
$longitude=$row['longitude'];
$result_array[]=array('latitude'=>$latitude,'longitude'=>$longitude);
}
$json=json_encode($result_array);
$con->close();
?>
<h3>MyMap</h3>
<div id="map"></div>
<script>
function initMap() {
var mapDiv = document.getElementById('map');
var map = new google.maps.Map(mapDiv, {
center: {lat: 41.5400 , lng: 12.2500},
zoom: 6
});
var array="<?php echo $json;?>";//here changed
for(var i=0;i<array.length;i++){
var myLatLng=new google.maps.LatLng(lat,lon);
var marker=new google.maps.Marker({
map:map,
position: myLatLng,
});
//}
}
</script>
<script async defer
src=MY GOOGLE API MAP>
</script>
</body>
</html>

Adding multiple markers to Google Maps with JavaScript and PHP

I am having difficulties adding multiple markers to my Google Map. Below is my code:
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(-35.3075,149.1244)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
<?php
$dbc = mysql_connect('localhost', 'username', 'password') or die('Unable to connect to MySQL: '.mysql_error());
mysql_select_db ('database', $dbc) or die('Unable to connect to database: '.mysql_error());
$query = "SELECT * FROM centenary_events WHERE location != ''";
$result = mysql_query($query) or die("Error querying database: ".mysql_error());
while ($row = mysql_fetch_array($result)) {
?>
<script>
var link = 'https://query.yahooapis.com/v1/public/yql?q=select%20*%20from%20geo.placefinder%20where%20text%3D"<?php echo $row['location']?>"&format=json&diagnostics=true';
$.getJSON(link, function(json) {
console.log("<?php echo $row['title']?>");
console.log("Latitude: " + json.query.results.Result.latitude);
console.log("Longitude: " + json.query.results.Result.longitude);
var marker = new google.maps.Marker({
position: new google.maps.LatLng(Number(json.query.results.Result.latitude), Number(json.query.results.Result.longitude)),
map: map,
title: 'Hello World!'
});
});
</script>
<?php
}
?>
</head>
<body>
<div id="map-canvas" style="width: 100%; height: 100%"></div>
</body>
</html>
Using PHP and MySQL, I am attempting to loop through a database to gather values, and then use those values to add markers to a map. The map is working, but the marker functionality is not. Please help.
You're not doing it in the way you need to :),
So to add multiple marker or what ever into map from php, the best way would be while proccesing the php fetch those data you wanna display and send them to javascript (json,xml or whatever js can parse) or playing with ajax (which is one level higher the this solution), in your case should be like the follow:
HTML&PHP
<?php
$dbc = mysql_connect('localhost', 'username', 'password') or die('Unable to connect to MySQL: '.mysql_error());
mysql_select_db ('database', $dbc) or die('Unable to connect to database: '.mysql_error());
$query = mysql_query("SELECT * FROM centenary_events WHERE location != ''");
$myData = array();
while($row = mysql_fetch_array($result)){
$myData = $row;
}
?>
<!DOCTYPE html>
<html>
<head>
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map-canvas { height: 100% }
</style>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp"></script>
<script>
//here is the magic :)
var myData = <?php echo json_encode($myData) ?>;
function initialize() {
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(-35.3075,149.1244)
}
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
//and you must set this code here because the map is just initialed
$.each(myData, function(){
var link = 'generate your link here with myData array';
$.getJSON(link, function(json) {
var marker = new google.maps.Marker({
position: new google.maps.LatLng(Number(json.query.results.Result.latitude), Number(json.query.results.Result.longitude)),
map: map,
title: 'Hello World!'
});
});
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
...
The code may have errors, I just wanted to create you an idea how it should look

Using values from mysql database to place marker on googlemaps

Im trying to pull values from mysql database and use to draw a marker on the map but it doesnt seem to work, I've tested the database connection and its working fine but i dont know what the problem is
<html>
<?PHP
include("config.php");
$sql="SELECT * FROM lat long";
$rs = mysqli_query($con,$sql) or die(mysql_error());
$array=mysqli_fetch_array($rs);
$Lat=$array['lat'];
$Lng=$array['long'];
?>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<style type="text/css">
html { height: 100% }
body { height: 100%; margin: 0; padding: 0 }
#map_canvas { height: 100% }
#select_route {width:20%;height:200px;}
</style>
<script type="text/javascript"
src="http://maps.googleapis.com/maps/api/js?sensor=false">
</script>
<script type="text/javascript">
var map = "";
function initialize() {
var mapOptions = {
center: new google.maps.LatLng(30, 31),
zoom: 5,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("map_canvas"),
mapOptions);
}
function addMarker() {
var LatLong= new google.maps.LatLng(<?php echo lat ?> ,<?php echo lng ?>);
//Problem Lies here in passing the lat and long i suppose
marker = new google.maps.Marker({
position:LatLong,
});
marker.setMap(map);
var infowindow = new google.maps.InfoWindow({
content: "<p style='color:blue'>UserInfo</p>" + '<button type="button">Navigate</button>' + '<IMG BORDER="0" ALIGN="Left" SRC="testpic.png">' ,
position: new google.maps.LatLng(30, 31),
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.open(map,marker);
});
};
</script>
<div id ="welcome" style="color:#0000FF">
<h3>Welcome to GoogleMaps </h3>
</div>
</head>
<body onload="initialize();addMarker();">
<div id="map_canvas" style="width:60%; height:80%"></div>
First thing that I saw is that you are missing the $ sign before the php variables in the following line:
var LatLong= new google.maps.LatLng(<?php echo lat ?> ,<?php echo lng ?>);
Also the variable names are not correct. You defined the variables as $Lng and $Lat starting with capital letters but in the above code you are using lowercase.
So change that line to:
var LatLong= new google.maps.LatLng(<?php echo $Lat ?> ,<?php echo $Lng ?>);
Besides this, you might have to adjust your query. It would make more sense if it was something along these lines:
"SELECT * FROM table_name" where table_name is the name of your table.
Finally, if it still does not work please post the javascript errors form your browser's console and the php error log to make it easier for me to see the errors.

Array alerts 0 for .length not sure why

I'm pretty new to JQuery, I'm trying to make an event so when table row is clicked it does something, but it will have a for loop, but that wasn't working so I removed the loop and did an alert to see how many items were inside of the array, it alerts 0. I'm not sure why, on page load the script generates markers from my database and loads them onto the map (That works fine and as intended) on the left side of the screen a table is made that says what street each stop is on, and when you click on the table row it is supposed to center and zoom on the marker (I can figure that part out on my own) But right now it's telling me there is nothing in the array and I'm not sure why. Thanks.
<?php
require_once('config.inc.php');
require_once($rootdir . $dirsubfolder . 'navbar.php');
include($rootdir . $dirsubfolder . 'php/findmarkers.php');
?>
<script>
$(document).ready(function() {
var arrMarkers = [];
var zoom = 6;
var initialLocation;
var map;
var markersArray = new Array();
$("table#listOfStops").find('tr').each(function() {
$(this).on('click', function() {
alert(arrMarkers.length);
});
});
$(window).resize(function () {
var h = $(window).height(),
offsetTop = 230; // Calculate the top offset
$('#gmaps').css('height', (h - offsetTop));
}).resize();
loadScript();
});
function initialize() {
geocode = new google.maps.Geocoder();
var mapOptions = {
zoom: 10,
center: new google.maps.LatLng(56.7626362, -111.379652),
mapTypeId: google.maps.MapTypeId.ROADMAP,
disableDefaultUI: false,
zoomControl: true,
zoomControlOptions: {
style: google.maps.ZoomControlStyle.LARGE
}
};
map = new google.maps.Map(document.getElementById('gmaps'),
mapOptions);
google.maps.event.addListener(map, 'click', function(event) {
var latitude = event.latLng.lat();
var longitude = event.latLng.lng();
deleteOverlays();
addMarker(event.latLng);
updateTextFields(latitude, longitude);
});
<?php while($stmt -> fetch()) { ?>
var long = "<?php echo $gLongitude ?>";
var lati = "<?php echo $gLatitude; ?>";
var title = "<?php echo $gTitle; ?>"
setMarker(lati, long, title);
<? } $stmt -> close(); $mysqli -> close();?>
}
function setMarker(lat,lon, markerTitle) {
var latLonMarker = new google.maps.LatLng(lat,lon);
marker = new google.maps.Marker({
position: latLonMarker,
map: map,
icon: 'icon.png',
title: markerTitle
});
google.maps.event.addListener(marker, 'dragend', function() {
$('#inputLatitude').val(this.getPosition().lat());
$('#inputLongitude').val(this.getPosition().lng());
});
arrMarkers.push(marker);
}
function loadScript() {
var script = document.createElement('script');
script.src = 'https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=true&' +
'callback=initialize';
document.body.appendChild(script);
}
</script>
<?php include($rootdir . $dirsubfolder . 'php/findmarkers.php'); ?>
<div style="padding-top: 5%; padding-bottom: 5%;">
<div class="container-fluid">
<div class="row-fluid">
<div class="span3 container hero-unit">
<h2 style="text-align: center;">Route <?php echo $gRouteNumber ?></h2>
<h4 style="text-align: center;" class="alert-info">Begins <? echo $gArrivalTime; ?></h4>
<br />
<table id="listOfStops" class="table table-striped">
<thead>
<tr>
<th>Stop #</th>
<th>Street Name</th>
</tr>
</thead>
<tbody>
<?php
$i = 0;
while($stmt -> fetch()) {
echo '<tr id="' . $i . '">';
echo '<td>' . $gStopNumber . '</td>';
echo '<td>' . $gStreetName . '</td>';
echo '</tr>';
$i++;} $stmt -> close(); $mysqli -> close(); ?>
</tbody>
</table>
</div>
<div class="span9">
<div id="gmaps"></div>
</div>
</div>
</div>
</div>
<?php
require_once('footer.php');
?>
As I already stated in my comment, you are declaring arrMarkers as a local variable in your document ready function.
That means, it is undefined in the setMarker function.
Try making it a global variable and you should be good.

Categories