Transfer json array from PHP to JS - javascript

I am trying to transfer a json array from PHP to JS
<?php
//controllo se sono presenti i parametri
if(isset($_GET['id_utente']) && isset($_GET['longitude']) && isset($_GET['latitude']))
{
//Recupero il valore dei parametri
$id_utente = $_GET['id_utente'];
$longitude= $_GET['longitude'];
$latitude = $_GET['latitude'];
}
$servername = "localhost";
$username = "realegr";
$password = "pass";
$dbname = "my_realegr";
// Create connection,
$conn = mysqli_connect($servername, $username, $password,$dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
echo "Connected successfully\n";
// Insert Data
$sql = "INSERT INTO Prova (id_utente, latitude, longitude)
VALUES ('" . $id_utente . "', '" . $longitude . "', '" . $latitude . "')
";
if (mysqli_query($conn, $sql)) {
echo "New record created successfully\n\r";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
// Execute query and save it in result
$sql = "SELECT latitude,longitude FROM Prova ORDER by reg_date DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) > 0) {
// output data of each row
/* while($row = mysqli_fetch_assoc($result)) {
echo "latitude: " . $row["longitude"]. " - longitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
*/
$row = mysqli_fetch_assoc($result);
echo json_encode([
'status' => true,
'latitude' => $row["longitude"],
'longitude' => $row["latitude"],
]);
mysqli_close($conn);
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<script async defer
src="https://maps.googleapis.com/maps/api/js?key=AIzaSyBkEtPH07_xBVh8dWBzCQYtWimkOUnPGMQ&callback=initMap"></script>
<style>
#map {
height: 400px;
width: 100%;
}
</style>
</head>
<body>
<h3>My Google Maps Demo</h3>
<div id="map"></div>
<script>
function initMap(){
var $request = $.get('http://realegr.altervista.org/PopolamentoTabella.php');
$request.done( function(data) {
alert(data);
var pasedData = JSON.parse(data);
var longi = parseFloat(pasedData.longitude);
var lati = parseFloat(pasedData.latitude);
var uluru = {lat: lati, lng: longi};
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 4,
center: uluru
});
var marker = new google.maps.Marker({
position: uluru,
map: map
});
})
}
</script>
</body>
</html>
The php script seems work well.It updates the DB and echo the JSON array,as it should.
But when I try to load the Maps it gives me some error:
Beside in console I have this:
further information:evry time I send data to DB( with a get request), the php script has to send (only)gps coordinates to JS,to show them on a google maps

Change your 'PopolamentoTabella.php' to this
<?php
$servername = "localhost";
$username = "YOURUSERNAME";
$password = "YOURPASSWORD";
$dbname = "YOUR DB";
// Create connection,
$conn = mysqli_connect($servername, $username, $password, $dbname);
// Check connection
if (!$conn) {
die("Connection failed: " . mysqli_connect_error());
}
//echo "Connected successfully\n";
//controllo se sono presenti i parametri
if (isset($_GET['id_utente']) && isset($_GET['longitude']) && isset($_GET['latitude'])) {
//Recupero il valore dei parametri
$id_utente = $_GET['id_utente'];
$longitude = $_GET['longitude'];
$latitude = $_GET['latitude'];
// Insert Data
$sql = "INSERT INTO Prova (id_utente, latitude, longitude)
VALUES ('" . $id_utente . "', '" . $longitude . "', '" . $latitude . "')
";
if (mysqli_query($conn, $sql)) {
//echo "New record created successfully\n\r";
} else {
echo "Error: " . $sql . "<br>" . mysqli_error($conn);
}
} else {
// Execute query and save it in result
$sql = "SELECT latitude,longitude FROM Prova ORDER by reg_date DESC LIMIT 1";
$result = mysqli_query($conn, $sql);
//if (mysqli_num_rows($result) > 0) {
// output data of each row
/* while($row = mysqli_fetch_assoc($result)) {
echo "latitude: " . $row["longitude"]. " - longitude: " . $row["latitude"]. "<br>";
}
} else {
echo "0 results";
}
*/
$row = mysqli_fetch_assoc($result);
echo json_encode([
'status' => true,
'latitude' => $row["longitude"],
'longitude' => $row["latitude"],
]);
}
//echo $longitude;
mysqli_close($conn);
?>

Related

Having trouble with datatable invalid JSON response

I keep having this error. I manage to track down the response by inspecting the dataTable which lead me to believe that this is the source of the problem. Please bear with me for I'm still a beginner in javascript and PHP.
image link to error:
source of error
here are my codes:
config.php
<?php
class dbConfig {
protected $serverName;
protected $userName;
protected $password;
protected $dbName;
function dbConfig() {
$this -> serverName = 'localhost';
$this -> userName = 'root';
$this -> password = '';
$this -> dbName = 'database';
}
}
?>
user.php
<?php
require('config.php');
class User extends dbconfig {
protected $hostName;
protected $userName;
protected $password;
protected $dbName;
private $userTable = 'user';
private $dbConnect = false;
public function __construct(){
if(!$this->dbConnect){
$database = new dbConfig();
$this -> hostName = $database -> serverName;
$this -> userName = $database -> userName;
$this -> password = $database -> password;
$this -> dbName = $database -> dbName;
$conn = new mysqli($this->hostName, $this->userName, $this->password, $this->dbName);
if($conn->connect_error){
die("Error failed to connect to MySQL: " . $conn->connect_error);
} else{
$this->dbConnect = $conn;
}
}
}
private function getData($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$data= array();
while ($row = mysqli_fetch_array($result, MYSQL_ASSOC)) {
$data[]=$row;
}
return $data;
}
private function getNumRows($query) {
$result = mysqli_query($this->dbConnect, $query);
if(!$result){
die('Error in query: '. mysqli_error());
}
$numRows = mysqli_num_rows($result);
return $numRows;
}
public function userList(){
$query = "SELECT * FROM ".$this->userTable." ";
if(!empty($_POST["search"]["value"])){
$query .= 'where(user_id LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_fname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_mname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_lname LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_address LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_contactnumber LIKE "%'.$_POST["search"]["value"].'%" ';
$query .= ' OR user_birthdate LIKE "%'.$_POST["search"]["value"].'%") ';
}
if(!empty($_POST["order"])){
$query .= 'ORDER BY '.$_POST['order']['0']['column'].' '.$_POST['order']['0']['dir'].' ';
} else {
$query .= 'ORDER BY id DESC ';
}
if($_POST["length"] != -1){
$query .= 'LIMIT ' . $_POST['start'] . ', ' . $_POST['length'];
}
$result = mysqli_query($this->dbConnect, $query);
$numRows = mysqli_num_rows($result);
$userData = array();
while ($user = mysqli_fetch_assoc($result)) {
$userRows = array();
$userRows[] = $user['user_id'];
$userRows[] = ucfirst($user['user_fname']);
$userRows[] = $user['user_mname'];
$userRows[] = $user['user_lname'];
$userRows[] = $user['user_address'];
$userRows[] = $user['user_contactnumber'];
$userRows[] = $user['user_birthdate'];
$userRows[] = '>button type="button" name="update" id="'.$user['user_id'].'"class="btn btn-warning btn-xs update"<Update>/button<';
$userRows[] = '>button type="button" name="delete" id="'.$user['user_id'].'"class="btn btn-danger btn-xs update"<Delete>/button<';
$userData[] = $userRows;
}
$output = array(
"draw" => intval($_POST["draw"]),
"recordsTotal" => $numRows,
"recordsFiltered" => $numRows,
"data" => $userData
);
echo json_encode($output);
}
}
?>
ajax.js
$(document).ready(function(){
var userRecords = $('#userList').DataTable({
"lengthChange": false,
"processing": true,
"serverSide": true,
"order":[],
"ajax":{
url:"process.php",
type: "POST",
data: {action: 'listUser'},
dataType: "json"
},
"columnDefs":[
{
"targets": [0, 6, 7],
"orderable": false,
},
],
"pageLength": 10
});
});
process.php
<?php
include('user.php');
$user = new User();
if (!empty($_POST['action']) && $_POST['action'] == 'listUser') {
$user -> userList();
}
?>

how can i get form data validate it with javascript and send it to database using php

I have tried to pass my data from ajax to php then to database but I find errors saying uncaught error - "undefined function is_ajax"
..............my js code................
var form = document.getElementById('form');
form.addEventListener("submit",validateForm)
function validateForm(e) {
e.preventDefault();
var name = document.forms["form"]["name"] .value;
var ml = document.forms["form"]["mail"] .value;
var num = document.forms["form"]["number"] .value;
var ctry = document.forms["form"]["country"] .value;
var date_in = document.forms["form"]["date_in"] .value;
var time_in = document.forms["form"]["time_in"] .value;
var time_out = document.forms["form"]["time_out"] .value;
$.ajax({
type: "POST",
url: "data.php",
data:{myname:name,myemail:ml,c_num:num,c_ctry:ctry,in_date:date_in,in_time:time_in,out_time:time_out},
success:function(reply){
var respOutPut = String(reply);
console.log("OutPut:" + respOutPut);
if (respOutPut.trim() == "not Ajax Request"){
}
},
error: function () {
console.log("Error:");
}
});
}
.......php..........
<?php
if (is_ajax()) {
if( $_POST["myname"] && isset($_POST["myemail"]) &&
isset($_POST["c_num"]) && isset($_POST["c_ctry"]) &&
isset($_POST["in_date"]) && isset($_POST["in_time"]) &&
isset($_POST["out_time"])){
$name = $_POST["myname"];
$email = $_POST["myemail"];
$number = $_POST["c_num"];
$country = $_POST["c_ctry"];
$arrival_d = $_POST["in_date"];
$arrival_t = $_POST["in_time"];
$dep_t = $_POST["out_time"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "triangle";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error . "<br>");
}
echo "Connected successfully<br>";
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS triangle";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . $conn->error."<br>";
}
$conn->close();
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error."<br>");
}
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS Customer (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL,
number VARCHAR(50),
country VARCHAR(50),
date_in VARCHAR(50),
time_in VARCHAR(50),
dep_time VARCHAR(50))";
if ($conn->query($sql) === TRUE) {
echo "Table customer created successfully<br>";
} else {
echo "Error creating customer table: " . $conn->error."<br>";
}
$conn->close();
$sql = "INSERT INTO customer (name, email, number,country,date_in,time_in,dep_time)
VALUES ('$_POST[myname]','$_POST[myemail]','$_POST[c_num]','$_POST[c_ctry]','$_POST[in_date]','$_POST[in_time]','$_POST[out_time]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
$conn->close();
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
}
?><?php
if (is_ajax()) {
if( $_POST["myname"] && isset($_POST["myemail"]) &&
isset($_POST["c_num"]) && isset($_POST["c_ctry"]) &&
isset($_POST["in_date"]) && isset($_POST["in_time"]) &&
isset($_POST["out_time"])){
$name = $_POST["myname"];
$email = $_POST["myemail"];
$number = $_POST["c_num"];
$country = $_POST["c_ctry"];
$arrival_d = $_POST["in_date"];
$arrival_t = $_POST["in_time"];
$dep_t = $_POST["out_time"];
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "triangle";
// Create connection
$conn = new mysqli($servername, $username, $password);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error . "<br>");
}
echo "Connected successfully<br>";
// Create database
$sql = "CREATE DATABASE IF NOT EXISTS triangle";
if ($conn->query($sql) === TRUE) {
echo "Database created successfully<br>";
} else {
echo "Error creating database: " . $conn->error."<br>";
}
$conn->close();
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error."<br>");
}
// sql to create table
$sql = "CREATE TABLE IF NOT EXISTS Customer (id INT(6) UNSIGNED AUTO_INCREMENT PRIMARY KEY,
name VARCHAR(30) NOT NULL,
email VARCHAR(30) NOT NULL,
number VARCHAR(50),
country VARCHAR(50),
date_in VARCHAR(50),
time_in VARCHAR(50),
dep_time VARCHAR(50))";
if ($conn->query($sql) === TRUE) {
echo "Table customer created successfully<br>";
} else {
echo "Error creating customer table: " . $conn->error."<br>";
}
$conn->close();
$sql = "INSERT INTO customer (name, email, number,country,date_in,time_in,dep_time)
VALUES ('$_POST[myname]','$_POST[myemail]','$_POST[c_num]','$_POST[c_ctry]','$_POST[in_date]','$_POST[in_time]','$_POST[out_time]')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully<br>";
} else {
echo "Error: " . $sql . "<br>" . $conn->error."<br>";
}
$conn->close();
}
function is_ajax() {
return isset($_SERVER['HTTP_X_REQUESTED_WITH']) &&
strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest';
}
}
?>
You can send your form data like this
var formData = $(form).serializeArray();
$.ajax({
type: "POST",
url: "data.php",
data:{formData},
success:function(reply){
var respOutPut = String(reply);
console.log("OutPut:" + respOutPut);
if (respOutPut.trim() == "not Ajax Request"){
}
},
error: function () {
console.log("Error:");
}
});
And in your php you can get them by $_POST.

Setting location markers for each location on google map

I have code that I'm using (I didn't write it myself) that creates a Polyline on top of a google map based on lon and lat entries I have in my DB. It's working well right now. I'd like to add a marker for each location that makes up the line on the map so I can click on it and see the time, lon and lat info from the DB record for that point.
Here is the current code:
<?php
function flightpath($days = 1) {
if (($days > 100) || ($days < 1) || (!is_numeric($days))) {
echo 'Please specify a correct number of days (maximum 100 days)';
return;
}
$flightpath_part[0] = "<script>
function initialize() {
var myLatLng = new google.maps.LatLng(";
$flightpath_part[1] = ");
var mapOptions = {
zoom: 11,
center: myLatLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
var map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
var flightPlanCoordinates = [
";
$flightpath_part[2] = "
];
var flightPath = new google.maps.Polyline({
path: flightPlanCoordinates,
strokeColor: '#FF0000',
strokeOpacity: 1.0,
strokeWeight: 3
});
flightPath.setMap(map);
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
";
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Connection with MySQL database failed!';
exit();
}
$query = "SELECT `log`, `lat`, `lon` FROM `location` WHERE `log` >= ( DATE_SUB( CURDATE( ), INTERVAL " . ($days -1) . " DAY ) ) AND user_id = '$user_idA' ORDER BY `log` ASC";
$result = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0) {
echo "<br /><br /><br /><center><p>You have no locations in your database for this period!</p></center>";
} else {
$lat_sum = 0;
$lon_sum = 0;
$loc_sum = 0;
$flightpath = '';
while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach ($line as $col_value) {
$lon = $line['lon'];
$lat = $line['lat'];
$lon_sum = $lon_sum + $lon;
$lat_sum = $lat_sum + $lat;
$loc_sum = $loc_sum + 1;
if ($lon && $lat) {
$flightpath .= " new google.maps.LatLng(";
$flightpath .= $line['lat'];
$flightpath .= ", ";
$flightpath .= $line['lon'];
$flightpath .= "),\r\n";
}
}
}
$lon_center = $lon_sum / $loc_sum;
$lat_center = $lat_sum / $loc_sum;
$flightpath = substr_replace($flightpath, "", -3);
$flightpath = $flightpath_part[0] . $lat_center . ', ' . $lon_center . $flightpath_part[1] . $flightpath . $flightpath_part[2];
}
mysqli_close($conn);
return $flightpath;
}
?>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&libraries=visualization"></script>
<?php echo flightpath($days); ?>
Since the database has the lon and lat coordinates stored you can use those to create the map markers. You could try something like:
function flightmarkers($days=1){
$conn = mysqli_connect($dbhost, $dbuser, $dbpass, $dbname);
if (mysqli_connect_errno()) {
echo 'Connection with MySQL database failed!';
exit();
}
$query = "SELECT `log`, `lat`, `lon` FROM `location` WHERE `log` >= ( DATE_SUB( CURDATE( ), INTERVAL " . ($days -1) . " DAY ) ) AND user_id = '$user_idA' ORDER BY `log` ASC";
$result = mysqli_query($conn, $query);
$rowcount = mysqli_num_rows($result);
if ($rowcount == 0) {
echo "<br /><br /><br /><center><p>You have no locations in your database for this period!</p></center>";
} else {
$flightmarkers= '';
while ($line = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
foreach ($line as $col_value) {
$lon = $line['lon'];
$lat = $line['lat'];
if ($lon && $lat) {
$flightmarkers.=
'marker = new google.maps.Marker({
position: new google.maps.LatLng('.$line['lat'].','.$line['lon'].'),
map: map
});
';
}
}
return $flightmarkers;
}
<?php echo flightpath($days); ?>
<?php echo flightmarkers($days); ?>
I can't test it and I wasn't sure of the point of *_sum vars considering they are statically set to 0 so they dont really do anything. I removed them for simplicity. This might at least get you started in the right direction.
This link has a good bit of info about map markers also Google Maps JS API v3 - Simple Multiple Marker Example

Having divs act as button objects to retrieve data

I populated a list using the following code.
I'm trying to make each of the objects retrieved from the server act like a button and when clicked throw a pop up box displaying address, date, and status. Is there anyway to do this? I've been looking into using Ajax but it is getting a little confusing as I have an html file and a php file that has all my javascript/php (the javascript relies on a php function) and from what I've read I would need to make another php file to service the request. How then would I reference it within my html file to do so? I may be making this harder than it needs to be.
Original Code:
<?php
function getjson(){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, lng, lat FROM information WHERE username = '" . $_SESSION['user_name'] . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
switch($row["status"]){
case 3:
echo '<div id= "content" style = "background-color: red" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
case 4:
echo '<div id= "content" style = "background-color: yellow" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
case 5:
echo '<div id= "content" style = "background-color: green" onclick = popinformation(' . $row["id"] . ')> ' . $row["address"] . "</div>";
break;
}
}
}
$db_connection->close();
}
function getalerts($id){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE id = '" . $id . "';";
$result = $db_connection->query($sql);
$temp = array();
$row = $result->fetch_assoc();
$temp[] = $row;
$db_connection->close();
return json_encode($temp);
}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function getlocations(){
var data = <?php echo getjson(); ?>;
var i = 0;
var locations = new Array();
for(i; i < data.length; i++){
var dataholder = [data[i].misc, parseFloat(data[i].lat), parseFloat(data[i].lng)];
locations.push(dataholder);
}
return locations;
}
function createmap(){
var locations = getlocations();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(47.624561, -122.356445),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
function popinformation(data){
var json = <?php getalerts(); ?>
console.log(json);
}
Update:
Here's what I was trying, from what I've read I have a misunderstanding of php/javascript. This is all my code within the file. Colors appear fine but pop-ups do not appear, Console reports Uncaught SyntaxError: Unexpected token < which will go away if I delete the final script. I think that means the error is within the echo json_encode($results) somehow.
<?php
function getjson(){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, lng, lat FROM information WHERE username = '" . $_SESSION['user_name'] . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
$colors = array(3 => 'red', 4 => 'yellow', 5 => 'green');
$results = array();
while ($row = $result->fetch_assoc()){
$results[$row['id']] = $row;
echo '<div class="content" style = "background-color: ' . $colors[$row['status']] . '" data-id="' . $row["id"] . '"> ' . $row["address"] . "</div>";
}
$db_connection->close();
}
function getalerts($id){
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT date, id, address, status FROM information WHERE id = '" . $id . "';";
$result = $db_connection->query($sql);
$temp = array();
while($row = $result->fetch_assoc()) {
$temp[] = $row;
}
$db_connection->close();
$json = json_encode($temp);
return $json;
}
?>
<script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
<script>
function getlocations(){
var data = <?php echo getjson(); ?>;
var i = 0;
var locations = new Array();
for(i; i < data.length; i++){
var dataholder = [data[i].misc, parseFloat(data[i].lat), parseFloat(data[i].lng)];
locations.push(dataholder);
}
return locations;
}
function createmap(){
var locations = getlocations();
var map = new google.maps.Map(document.getElementById('map'), {
zoom: 13,
center: new google.maps.LatLng(47.624561, -122.356445),
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var infowindow = new google.maps.InfoWindow();
var marker, i;
for (i = 0; i < locations.length; i++) {
marker = new google.maps.Marker({
position: new google.maps.LatLng(locations[i][1], locations[i][2]),
map: map
});
google.maps.event.addListener(marker, 'click', (function(marker, i) {
return function() {
infowindow.setContent(locations[i][0]);
infowindow.open(map, marker);
}
})(marker, i));
}
}
</script>
<script>
$(document).ready(function() {
var information_object = <?php echo json_encode($results); ?>;
$(".content").click(function() {
var info = information_object[$(this).data('id')];
if (info) {
alert("Address: " + info.address + "\nDate: " + info.date + "\nStatus: " + info.status);
} else {
alert("Invalid ID: " + id);
}
});
});
My html Document
<html>
<head>
<link rel="stylesheet" href="css/logged_in.css">
<?php
include("login_php_scripts.php");
?>
</head>
<body>
<div id="navigation">
Account
Logout
</div>
<div id="header">
<div id="logo"></div>
<div id="header_text"></div>
</div>
<div id="content_wrapper">
<div id="list_view">
I am logged in as: <?php echo $_SESSION['user_name']; ?></br>
<?php
getwarnings();
?>
</div>
<div id="map">
<script>
createmap();
</script>
</div>
</div>
<div id="footer"></div>
</body>
</html>
Put all the database results into an array, then convert that to a Javascript object that your popup function can look up by ID.
function getwarnings(){
$username = $_SESSION['user_name'];
$db_connection = new mysqli(DB_HOST, DB_USER, DB_PASS, DB_NAME);
if(mysqli_connect_errno()){
echo "Failed to connect to Mysql: " . mysqli_connect_error();
}
$sql = "SELECT misc, date, id, address, status FROM information WHERE username = '" . $username . "';";
$result = $db_connection->query($sql);
$colors = array(3 => 'red', 4 => 'yellow', 5 => 'green');
$results = array();
while ($row = $result->fetch_assoc()){
$results[$row['id']] = $row;
echo '<div class="content" style = "background-color: ' . $colors[$row['status']] . '" data-id="' . $row["id"] . '"> ' . $row["address"] . "</div>";
}
$db_connection->close();
?>
<script>
$(document).ready(function() {
var information_object = <?php echo json_encode($results); ?>;
$(".content").click(function() {
var info = information_object[$(this).data('id')];
if (info) {
alert("Address: " + info.address + "\nDate: " + info.date + "\nStatus: " + info.status);
} else {
alert("Invalid ID: " + id);
}
});
});
</script>
<?php
}

Google Map is not appearing when connecting to database

I want to retrieve geocodes from a database using PHP and MySQL with JSON. It works by selecting an option from a drop-down list and reading the matching data. I think the functions of PHP and MySQL are working correctly is just some problem with JavaScript and the map.
Code for the JavaScript:
<div data-role="content" id="accommodation">
<div id="Manu">
<select id="Cheltenham"></select>
<!--Map-->
<div id="myMap">
<script type="text/javascript">
/* call the php that has the php array which is json_encoded */
$.getJSON('cheltenham.php', function(data){
/* data will hold the php array as a javascript object */
$.each(data, function(key, val){
var x = document.getElementById("Cheltenham");
var option = document.createElement("option");
option.text = val.BUSTYPE;
option.value = val.REFERENCE;
x.add(option);
})
});
function initialize(){
$(document).on('click', '#Cheltenham', function() {
var referenceID = $(this).selected.value;
$.getJSON('SearchBusinesses.php?ReferenceID='+referenceID, function(data) {
ev_ref = data.REFERENCE;
ev_busid = data.BUSID
ev_name = data.NAME;
lat = parseFloat(data.LATITUDE);
longi = parseFloat(data.LONGITUDE);
});
var map;
var myLatlng = new google.maps.LatLng(lat,longi);
var geocoder = new google.maps.Geocoder();
var infowindow = new google.maps.InfoWindow();
var mapOptions = {
zoom: 15,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
map = new google.maps.Map(document.getElementById("myMap"), mapOptions);
showMarker();
function showMarker() {
marker = new google.maps.Marker({
map: map,
position: myLatlng,
draggable: true
});
geocoder.geocode({'latLng': myLatlng }, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
if (results[0]) {
var marker = new google.maps.Marker({map: map, position:results[0].geometry.location});
infowindow.setContent(ev_name + '<br/>' + lat + '<br/>' + long);
infowindow.open(map, marker);
}
}
});
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</div>
</div>
</div>
Code for cheltenham.php:
<?php
$servername = "localhost";
$username = "secret";
$password = "secret";
$dbname = "secret";
function getEventList(){
global $servername, $username, $password, $dbname;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM `BUSINESS_TYPE`";
$result = $conn->query($sql);
$rows = array();
if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
$rows[] = $row;
}
} else {
//echo "0 results" . "<br>";
}
$conn->close();
echo json_encode($rows);
}
getEventList();
?>
Code for SearchBusinesses.php
<?php
$servername = "localhost";
$username = "secret";
$password = "secret";
$dbname = "secret";
$evReference = $_GET['REFERENCE'];
function getEventOne(){
global $servername, $username, $password, $dbname, $evName;
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT `LATITUDE`, `LONGITUDE` FROM `BUSINESSES` where `REFERENCE` = '" . $evReference . "'";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
$row = $result->fetch_assoc();
echo json_encode($row);
} else {
//echo "0 results" . "<br>";
}
$conn->close();
}
getEventOne();
?>
add this line to cheltenham.php
echo json_encode($rows, JSON_FORCE_OBJECT);

Categories