How to save the text box data in mysql table - php

I am using a map to obtain the co ordinates of the location, and get it on my text box named "add". When I try to insert the data obtained from the text box into the table it shows error.
This is my code below:
<html>
<head>
<link href="modal.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form action="" method="POST">
<table>
<tr><td>
</br>GIS Stamp</td>
<td><br><input type="text" name="add" id="add" size="31" value="" disabled="disabled"/><a href="#login_form" id="login_pop">
Select From MAP</a>
<div class="popup">
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
<script type="text/javascript">
var geocoder = new google.maps.Geocoder();
function geocodePosition(pos) {
geocoder.geocode({
latLng: pos
}, function(responses) {
if (responses && responses.length > 0) {
updateMarkerAddress(responses[0].formatted_address);
} else {
updateMarkerAddress('Cannot determine address at this location.');
}
});
}
function updateMarkerStatus(str) {
document.getElementById('markerStatus').innerHTML = str;
}
function updateMarkerPosition(latLng) {
document.getElementById('info').innerHTML = [
latLng.lat(),
latLng.lng()
].join(', ');
add.value=[
latLng.lat(),
latLng.lng()
].join(', ');
}
function updateMarkerAddress(str) {
document.getElementById('address').innerHTML = str;
}
function initialize() {
var latLng = new google.maps.LatLng(12.941320125683307, 74.86030859375);
var map = new google.maps.Map(document.getElementById('mapCanvas'), {
zoom: 8,
center: latLng,
mapTypeId: google.maps.MapTypeId.ROADMAP
});
var marker = new google.maps.Marker({
position: latLng,
title: 'Point A',
map: map,
draggable: true
});
// Update current position info.
updateMarkerPosition(latLng);
geocodePosition(latLng);
// Add dragging event listeners.
google.maps.event.addListener(marker, 'dragstart', function() {
updateMarkerAddress('Dragging...');
});
google.maps.event.addListener(marker, 'drag', function() {
updateMarkerStatus('Dragging...');
updateMarkerPosition(marker.getPosition());
});
google.maps.event.addListener(marker, 'dragend', function() {
updateMarkerStatus('Drag ended');
geocodePosition(marker.getPosition());
});
}
// Onload handler to fire off the app.
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<style>
#mapCanvas {
width: 500px;
height: 400px;
float: left;
}
#infoPanel {
display:none;
float: left;
margin-left: 10px;
}
#infoPanel div {
margin-bottom: 5px;
}
</style>
<div id="mapCanvas"></div>
<div id="infoPanel">
<b>Marker status:</b>
<div id="markerStatus"><i>Click and drag the marker.</i></div>
<b>Current position:</b>
<div id="info"></div>
<b>Closest matching address:</b>
<div id="address"></div>
</div>
</body>
</html>
<a class="close" href="#close"></a>
</div><br></td>
</tr>
<!-- panel with buttons -->
<tr><td>
<input type="submit" name="submit" value="Insert"></td></tr></table>
</body>
</form>
</html>
<?php
if(isset($_POST['submit']))
{
$add=$_POST['add'];
$c=mysql_connect("localhost","root","");
mysql_select_db("hudadb");
$ins=mysql_query("INSERT INTO `death`
(GIS)
VALUES ('$add')",$c) or die(mysql_error());
}
?>
The error I'm getting is:
Notice: Undefined index: add in D:\XAMPP\htdocs\hudaf\mainproj\s\s.php

Elements with Disabled attribute are not submitted or you can say their values are not posted.
Replace this line of code
<input type="text" name="add" id="add" size="31" value="" disabled="disabled"/>
with
<input type="text" name="add" id="add" size="31" value="" readonly/>
NOTE: Remember disabled field is not submitted with form submit, you need to use readonly for that.

Related

put selected values from textbox and dropdown to a basket like amazon

I have a PHP survey form in which there is a question "Which are your favourite movies?". for this question, I put a dropdown which enable users to select movies by title or by actor. If user select "by title", a textbox (auto-complete) will be shown where he can insert a movie name. If user select "by actor", a new window will be opened containing a textbox where user should insert an actor name, then a dynamic dropdown is populated showing list of movies by that actor.
Question:
How can I get the selected movies (from textbox and also dropdown in new window) and put them in a basket like amazon shopping cart? I searched a lot, but I really could not find the solution.. I can put the selected values in a new dropdown, but my professor asked me to use the same method like amazon and put them in a basket!!
UPDATE:
Here is what I have tried:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
</head>
<body>
<div class="movienames">
<select id="selectType" name="source" style="size=5px; width:100px; height:30px;">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
<option value="byDirector">byDirector</option>
</select>
<div id="m_scents">
<p>
<label style="margin-bottom:10px;" for="m_scnts"></label>
<input class="autofill4" type="textbox" name= "q27[]" id="q" style="display:none;" placeholder="Enter movie titles here" />
<!--Add more movies-->
<input type="button" value=">> Add to selected list >>" id="btnMove" style="display:none;"/>
<input name="s" value="all" type="hidden"/>
<label style="margin-bottom:10px;" for="m_scnts"></label>
</p>
</div>
<select id="selectedItems" name="selectedItems[]" multiple="multiple" style="width:200px; size:10px;">
</select>
<script type="text/javascript">
$(document).ready(function () {
$("#selectType").change(function () {
if ($(this).val() == "byTitle") {
$("#q").show();
$("#btnMove").show();
$("#q").focus();
$("#q").autocomplete({
minLength: 0,
delay:5,
source: "mona.php",
focus: function( event, ui ){
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function( event, ui ) {
$(this).val( ui.item.movieName );
return false;
}
}).data("uiAutocomplete")._renderItem = function( ul, item ) {
return $("<li></li>")
.data( "item.autocomplete", item )
.append( "<a>" + (item.posterLink?"<img class='imdbImage' src='imdbImage.php?url=" + item.posterLink + "' />":"") + "<span class='imdbTitle'>" + item.movieName + "</span>" + "<div class='clear'></div></a>" )
.appendTo( ul );
};
} else
if ($(this).val() == "byActor"){
window.open("target.html","_blank","height=400,width=400, status=yes,toolbar=no,menubar=no,location=no");
}
});
});
$('#btnMove').on('click', function (d) {
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
}
$('#selectedItems').append(new Option(selected));
var title = new Option(selected);
$("#q").val("");
d.preventDefault();
});
</script>
</body>
</html>
and this is target.html:
<html>
<head>
<link type="text/css" href="res/jquery-ui.css" rel="stylesheet" />
<script type="text/javascript" src="res/jquery.min.js"></script>
<script type="text/javascript" src="res/jquery-ui.min.js"></script>
<script src="http://thecodeplayer.com/uploads/js/prefixfree-1.0.7.js"type="text/javascript"type="text/javascript"></script>
</head>
<body>
<form>
<p>
<input type="textbox" name= "tag" id="tags" placeholder="Enter an actor/actress name here" />
</p>
<p>
<select id="movieName" name="movieName[]" multiple="multiple" width="200px" size="10px" style="display:none;">
</select>
</p>
<script type="text/javascript">
$(document).ready(function () {
$("#tags").autocomplete({
source: "actorsauto.php",
minLength: 2,
focus: function( event, ui ){
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function (event, ui){
var selectedVal = ui.item.value;
$.post("actions.php", {q: selectedVal}, function (response){
console.log(response);
$("#movieName").html(response).show();
});
}
});
});
</script>
</form>
</body>
</html>
Could someone kindly inform me if there is any tutorial or sample that I can use for this purpose?
All ideas are highly appreciated,
Thanks
ok for the first part I would do the following:
HTML:
<html>
<head>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<link rel="stylesheet" href="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/themes/smoothness/jquery-ui.css" />
<script src="//ajax.googleapis.com/ajax/libs/jqueryui/1.11.2/jquery-ui.min.js"></script>
<style>
#basket{
padding: 10px;
border:1px solid #ccc;
}
#basket h3{
padding: 0;
margin: 0;
}
</style>
</head>
<body>
<div class="movienames">
<select id="selectType" name="source" style="font-size:15px; width:100px; height:30px;">
<option value="">MoviesBy</option>
<option value="byTitle">byTitle</option>
<option value="byActor">byActor</option>
<option value="byDirector">byDirector</option>
</select>
<div id="m_scents">
<p>
<label style="margin-bottom:10px;" for="m_scnts"></label>
<input class="autofill4" type="textbox" name= "q27[]" id="q" style="display:none;" placeholder="Enter movie titles here" />
<!--Add more movies-->
<input type="button" value=">> Add to selected list >>" id="btnMove" style="display:none;"/>
<input name="s" value="all" type="hidden"/>
<label style="margin-bottom:10px;" for="m_scnts"></label>
</p>
</div>
<div id="basket">
<h3>Basket</h3>
<div id="basket_content">
</div>
</div>
JS:
var master_basket = new Array();
$(document).ready(function() {
$("#selectType").change(function() {
if ($(this).val() == "byTitle") {
$("#q").show();
$("#btnMove").show();
$("#q").focus();
$("#q").autocomplete({
minLength: 0,
delay: 5,
source: "mona.php",
focus: function(event, ui) {
event.preventDefault(); //This prevent the inserted text to be changed while moving in suggest list
return false;
},
select: function(event, ui) {
$(this).val(ui.item.movieName);
return false;
}
}).data("uiAutocomplete")._renderItem = function(ul, item) {
return $("<li></li>")
.data("item.autocomplete", item)
.append("<a>" + (item.posterLink ? "<img class='imdbImage' src='imdbImage.php?url=" + item.posterLink + "' />" : "") + "<span class='imdbTitle'>" + item.movieName + "</span>" + "<div class='clear'></div></a>")
.appendTo(ul);
};
} else
if ($(this).val() == "byActor") {
window.open("target.html", "_blank", "height=400,width=400, status=yes,toolbar=no,menubar=no,location=no");
}
});
});
$('#btnMove').on('click', function(d) {
d.preventDefault();
var selected = $("#q").val();
if (selected.length == 0) {
alert("Nothing to move.");
d.preventDefault();
} else {
addToBasket(selected);
}
$("#q").val("");
});
function addToBasket(item) {
master_basket.push(item);
showBasketObjects();
}
function showBasketObjects() {
$("#basket_content").empty();
$.each(master_basket, function(k, v) {
$("#basket_content").append("<div>" + v + "</div>");
});
}

How to get google maps from city got from a PHP input form?

I am trying to get a Google map displaying location information based on the IP address geolocation from a form submission.
The below PHP code work like this: If I enter an IP Address in the text box, it will give me city and country. I need to automatically get Google maps for the corresponding city:
<html>
<body>
<?php
if( !defined('LOADED') )
die('You cannot access this file directly!');
function countryCityFromIP($ipAddr)
{
$url = "http://api.ipinfodb.com/v3/ip-city/?key=5cfaab6c5af420b7b0f88d289571b990763e37b66761b2f053246f9db07ca913&ip=$ipAddr&format=json";
$d = file_get_contents($url);
return json_decode($d , true);
}
if(isset($_REQUEST['submit'])){
$ip=countryCityFromIP($_REQUEST['ip']);
//print_r($ip);
$myString = "The City for the entered IP Address= ";
$myString2 = "The Country for the entered IP Address= ";
echo "<p style='text-align: center; font-size: 25px; font-family: georgia,palatino; color: #202020;'>".$myString.$ip['cityName']."</p>";
echo "<p style='text-align: center; font-size: 25px; font-family: georgia,palatino; color: #202020;'>".$myString2.$ip['countryName']."</p>";
}
?>
<form method="post">
<center><input type="text" name="ip" style="font-size:25pt;height:30px;width:400px"/></center>
<center><input type="submit" name="submit" value="Search IP Location" style="font-size:15pt;height:40px;width:200px"/></center>
</form>
</body>
Code where you can get map for desired place.
LOOK FOR GOOGLE GEOCODE FOR MORE INFO
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no">
<meta charset="utf-8">
<title>Geocoding service</title>
<link href="/maps/documentation/javascript/examples/default.css" rel="stylesheet">
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false"></script>
<script>
var geocoder;
var map;
function initialize() {
geocoder = new google.maps.Geocoder();
var latlng = new google.maps.LatLng(-34.397, 150.644);
var mapOptions = {
zoom: 8,
center: latlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
map = new google.maps.Map(document.getElementById('map-canvas'), mapOptions);
}
function codeAddress() {
var address = document.getElementById('address').value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
map.setCenter(results[0].geometry.location);
var marker = new google.maps.Marker({
map: map,
position: results[0].geometry.location
});
} else {
alert('Geocode was not successful for the following reason: ' + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<div id="panel">
<input id="address" type="textbox" value="Sydney, NSW">
<input type="button" value="Geocode" onclick="codeAddress()">
</div>
<div id="map-canvas"></div>
</body>
</html>
You can manupulate this code acording to your needs,
var address = document.getElementById('address').value;
in var address you have to pass your $myString.$ip['cityName']. variable . hope this helps

Updating div on button click, when the button is generated by clicking on another button

On clicking the button magic1 or magic2, the div mybox will be updated with a text, button id and button (different for magic1 and magic2).
After clicking on the newly generated button it should display the button id of the newly generated button in the box div. When I click on the newly generated button, box div is not getting updated. Here is the code.
jquerycode.php is the initial file. On clicking the button magic1 or magic2, Ajax will call the page session.php.
jquerycode.php file
<!doctype html>
<?php
$first=$_POST['q'];
echo $first;
?>
<html>
<head>
<meta charset="utf-8" />
<title>My jQuery Ajax test</title>
<style type="text/css">
#mybox {
width: 300px;
height: 250px;
border: 1px solid #999;
}
#box {
width: 300px;
height: 250px;
border: 1px solid #999;
position: absolute;
right:210px;
}
</style>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$(".magic_button").click(function() {
var data = $(this).attr('id');
//alert (data);
$.ajax({
type: "POST",
url: "session.php",
data: { 'id': data }
}).done(function(msg) {
$("#mybox").html(msg);
});
});
});
</script>
<script>
$(".fir").click(function() {
var dataa = $(this).attr('id');
alert ("hello");
$.ajax({
type: "POST",
url: "jquerycode.php",
data: { 'q': dataa }
}).done(function(msg) {
$("#box").html(msg);
return false;
});
});
</script>
</head>
<body>
The following div will be updated after the call:<br />
<div id="mybox">
</div>
<div id="box">
</div>
<form name="magic">
<!-- <label for="name" id="name_label">Name</label>
<input type="text" name="name" id="name" size="30" value="" class="text-input" />
<label class="error" for="name" id="name_error">This field is required.</label> -->
<input type="button" class="magic_button" name="magic_button" id="magic_button_1" value="magic1" />
<input type="button" class="magic_button" name="magic_button" id="magic_button_2" value="magic2" />
</form>
</body>
</html>
session.php file
<?php
$id = $_POST['id'];
$id = ucwords(implode(' ',explode('_',$id)));
if($id==="Magic Button 2")
{
echo "hey its button 2!!";
?>
<input type="button" name="butb" id="second" class="fir" value="second"/>
<?php
}
else
{
echo "hey its button 1!!";
?>
<input type="button" name="buta" id="first" class="fir" value="First"/>
<?php
}
echo $id;
?>
Best if you can use JQuery Live() for dynamic Generated Elements :
$("a.offsite").live("click", function(){ alert("Goodbye!"); }); // jQuery 1.3+
Beca JQuery Live() is deprecated you need to use JQuery on()
$("#elementid").on("click", function(event){
alert($(this).text());
});

Google Map Fails to Load

I tested this code on a test page but now want to implement it on a page that is called by an overlay (Lightview). The map is not displaying and I do not know why. The overlay spaces the size of a map, but nothing shows. Here is the code:
<head>
<meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
<meta http-equiv="content-type" content="text/html; charset=UTF-8"/>
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"> </script>
<?php
require_once('../maps/google.php');
if(isset($_POST['submit']))
{
$zipcode = $_REQUEST['zipcode'];
$lookupPerformed = false;
if (strlen($zipcode) > 0) {
$geocoder = new Geocoder('mykey');
try {
$placemarks = $geocoder->lookup($zipcode);
}
catch (Exception $ex) {
echo $ex->getMessage();
exit;
}
$lookupPerformed = true;
}
foreach ($placemarks as $placemark) {
$lat = $placemark->getPoint()->getLatitude();
$long = $placemark->getPoint()->getLongitude();
}
?>
<script type="text/javascript">
//<![CDATA[
var customIcons = {
A Company: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
};
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(<?php echo $lat;?>, <?php echo $long;?>),
zoom: 10,
mapTypeId: 'roadmap'
});
var infoWindow = new google.maps.InfoWindow;
// Change this depending on the name of your PHP file
downloadUrl("../testxml.php?zipcode=<?php echo $zipcode;?>", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
for (var i = 0; i < markers.length; i++) {
var name = markers[i].getAttribute("name");
var address = markers[i].getAttribute("address");
var type = markers[i].getAttribute("type");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("lat")),
parseFloat(markers[i].getAttribute("lng")));
var html = "<b>" + name + "</b> <br/>" + address;
var icon = customIcons[type] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
icon: icon.icon,
shadow: icon.shadow
});
bindInfoWindow(marker, map, infoWindow, html);
}
});
}
function bindInfoWindow(marker, map, infoWindow, html) {
google.maps.event.addListener(marker, 'click', function() {
infoWindow.setContent(html);
infoWindow.open(map, marker);
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
//]]>
</script>
///// other PHP code
</head>
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value=" <?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
You have a pile of things going wrong here, and somethings which I can't even see to tell you whether they are right or wrong...
At the bottom of the posted code, you have:
</head>
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value=" <?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<body onload="load()">
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
You have a <form>...</form> element declared outside of the <body>...</body> tags - this is not valid HTML.
</head>
<body onload="load()">
<form method="POST" id="ajaxForm" onsubmit="submitAjaxFormDemonstration()">
<input type="text" size="10" maxlength="10" name="zipcode" tabindex="1" value="<?php echo $_POST['zipcode'];?>" />
<input type="submit" id="submit" value="Search" name="submit" tabindex="2" />
</form>
<div id="map" style="width: 500px; height: 300px"></div>
</body>
</html>
Fixes that... But you should probably use something like the W3C Validator to check your HTML code. Bad HTML will almost always break Javascript (like Google Maps).
Next, you are invoking a PHP script which you do not explain at all require_once('../maps/google.php');. What is it? Where did you get it? Have you consulted their Tutorials or Documentation?
You are only showing us part of the problem here. You need to go back to Square 1 and check each step as you move forwards. Jumping to the end (which, from the looks of your code, is what you've tried to do) means that one of the hundred steps between Square 1 and there may have broken, and now you have to go back and look for it.

Load mySQL Data Into Form

I am using the PHP and AJAX coding below to populate a map showing various markers for a given location stored in a mySQL database.
The markers are correctly shown but what I would like to be able to do is to populate the fields on my form with the associated data from the database, so that as each marker is clicked the fields will show the data pertient to that marker.
PHP Code
<
?php
require("phpfile.php");
// Start XML file, create parent node
$dom = new DOMDocument("1.0");
$node = $dom->createElement("markers");
$parnode = $dom->appendChild($node);
// Opens a connection to a MySQL server
$connection=mysql_connect ("hostname", $username, $password);
if (!$connection) { die('Not connected : ' . mysql_error());}
// Set the active MySQL database
$db_selected = mysql_select_db($database, $connection);
if (!$db_selected) {
die ('Can\'t use db : ' . mysql_error());
}
// Select all the rows in the markers table
$query = "SELECT findid, locationid, findosgb36lat, findosgb36lon, dateoftrip, findcategory, findname, finddescription, pasref, findimage, additionalcomments FROM finds WHERE `locationid` = '2'";
$result = mysql_query($query);
if (!$result) {
die('Invalid query: ' . mysql_error());
}
header("Content-type: text/xml");
// Iterate through the rows, adding XML nodes for each
while ($row = #mysql_fetch_assoc($result)){
// ADD TO XML DOCUMENT NODE
$node = $dom->createElement("marker");
$newnode = $parnode->appendChild($node);
$newnode->setAttribute("findid",$row['findid']);
$newnode->setAttribute("locationid",$row['locationid']);
$newnode->setAttribute("findosgb36lat",$row['findosgb36lat']);
$newnode->setAttribute("findosgb36lon",$row['findosgb36lon']);
$newnode->setAttribute("dateoftrip",$row['dateoftrip']);
$newnode->setAttribute("findcategory",$row['findcategory']);
$newnode->setAttribute("findname",$row['findname']);
$newnode->setAttribute("finddescription",$row['finddescription']);
$newnode->setAttribute("pasref",$row['pasref']);
$newnode->setAttribute("findimage",$row['findimage']);
$newnode->setAttribute("additionalcomments",$row['additionalcomments']);
}
echo $dom->saveXML();
?>
HTML Code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Finds Per Location</title>
<link rel="stylesheet" href="css/findsperlocationstyle.css" type="text/css" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
var customIcons = {
Artefact: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Coin: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Jewellery: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// Creating a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var findid = markers[i].getAttribute("findid");
var locationid = markers[i].getAttribute("locationid");
var dateoftrip = markers[i].getAttribute("dateoftrip");
var findcategory = markers[i].getAttribute("findcategory");
var findname = markers[i].getAttribute("findname");
var finddescription = markers[i].getAttribute("finddescription");
var pasref = markers[i].getAttribute("pasref");
var findimage= markers[i].getAttribute("findimage");
var additionalcomments= markers[i].getAttribute("additionalcomments");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var icon = customIcons[findcategory] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow
});
bounds.extend(point);
map.fitBounds(bounds);
}
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onLoad="load()">
<form name="findsperlocation" id="findsperlocation">
<p align="left"><label>Location id<br />
</label>
</p>
<div>
<div align="left">
<input name="locationid" type="text" id="locationid" value="2" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Date of Trip<br />
</label>
</p>
<div>
<div align="left">
<input name="dateoftrip" type="text" id="dateoftrip" readonly="readonly"/>
</div>
</div>
<p align="left">
<label></label>
<label>Find Category</label>
</p>
<div>
<div align="left">
<input name="findcategory" type="text" id="findcategory" size="10"readonly="readonly"/>
</div>
</div>
<p align="left">
<label>Find Name</label>
</p>
<div>
<div align="left">
<input name="findname" type="text" id="findname" size="35" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Find Description</label> </p>
<div>
<div align="left">
<input name="finddescription" type="text" id="finddescription" size="100"readonly="readonly"/>
</div>
</div>
<p align="left">
<label>
<label>PAS Ref. </label>
</p>
<div>
<div align="left">
<input name="pasref" type="text" id="pasref" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Additional Comments</label>
</p>
<div>
<div align="left">
<textarea name="additionalcomments" cols="50" rows="12" id="additionalcomments" readonly="readonly"></textarea>
</div>
</div>
<p align="left"><br />
</label>
</p>
<div>
<div align="left"></div>
</div>
</form>
<div id="map"></div>
</body>
</html>
I think I'm half way there because I'm mangaing to pull all of the information from the database. I can see this when I run the php script in my web browser, but I'm just not sure what to do for the next step.
What do I need to do next?
UPDATED CODE
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Finds Per Location</title>
<link rel="stylesheet" href="css/findsperlocationstyle.css" type="text/css" media="all" />
<script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false&language=en"></script>
<script type="text/javascript">
var customIcons = {
Artefact: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_red.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Coin: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_green.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
},
Jewellery: {
icon: 'http://labs.google.com/ridefinder/images/mm_20_yellow.png',
shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
}
};
// Creating a LatLngBounds object
var bounds = new google.maps.LatLngBounds();
function load() {
var map = new google.maps.Map(document.getElementById("map"), {
center: new google.maps.LatLng(54.312195845815246,-4.45948481875007),
zoom:14,
mapTypeId: 'satellite'
});
// Change this depending on the name of your PHP file
downloadUrl("phpfile.php", function(data) {
var xml = data.responseXML;
var markers = xml.documentElement.getElementsByTagName("marker");
var bounds = new google.maps.LatLngBounds();
for (var i = 0; i < markers.length; i++) {
var findid = markers[i].getAttribute("findid");
var locationid = markers[i].getAttribute("locationid");
var dateoftrip = markers[i].getAttribute("dateoftrip");
var findcategory = markers[i].getAttribute("findcategory");
var findname = markers[i].getAttribute("findname");
var finddescription = markers[i].getAttribute("finddescription");
var detectorname = markers[i].getAttribute("detectorname");
var searchheadname = markers[i].getAttribute("searchheadname");
var detectorsettings = markers[i].getAttribute("detectorsettings");
var pasref = markers[i].getAttribute("pasref");
var findimage= markers[i].getAttribute("findimage");
var additionalcomments= markers[i].getAttribute("additionalcomments");
var point = new google.maps.LatLng(
parseFloat(markers[i].getAttribute("findosgb36lat")),
parseFloat(markers[i].getAttribute("findosgb36lon")));
var icon = customIcons[findcategory] || {};
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow,
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory"
});
bounds.extend(point);
map.fitBounds(bounds);
}
google.maps.event.addListener(marker, "click", function() { alert("Associated data: " + this.formdateoftrip + ", " + this.findcategory); });
});
}
function downloadUrl(url, callback) {
var request = window.ActiveXObject ?
new ActiveXObject('Microsoft.XMLHTTP') :
new XMLHttpRequest;
request.onreadystatechange = function() {
if (request.readyState == 4) {
request.onreadystatechange = doNothing;
callback(request, request.status);
}
};
request.open('GET', url, true);
request.send(null);
}
function doNothing() {}
</script>
</head>
<body onLoad="load()">
<form name="findsperlocation" id="findsperlocation">
<p align="left"><label>Location id<br />
</label>
</p>
<div>
<div align="left">
<input name="locationid" type="text" id="locationid" value="2" readonly="readonly"/>
</div>
</div>
<p align="left"><label>Date of Trip<br />
</label>
</p>
<div>
<div align="left">
<input name="dateoftrip" type="text" id="dateoftrip" readonly="readonly"/>
</div>
</div>
<p align="left">
<label></label>
<label>Find Category</label>
</p>
<div>
<div align="left">
<input name="findcategory" type="text" id="findcategory" size="10"readonly="readonly"/>
</div>
</div>
</form>
<div id="map"></div>
</script>
</body>
</html>
CODE SNIPPET
var marker = new google.maps.Marker({
map: map,
position: point,
title: 'Click to view details',
icon: icon.icon,
shadow: icon.shadow,
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory",
formfindname: "findname",
formfinddescription: "finddescription",
formpasref: "pasref",
formfindimage: "findimage",
formadditionalcomments: "additionalcomments"
});
bounds.extend(point);
map.fitBounds(bounds);
}
google.maps.event.addListener(marker, "click", function() {
document.getElementById('dateoftrip').value = this.formdateoftrip;
document.getElementById('findcategory').value = this.formfindcategory;
document.getElementById('findname').value = this.formfindname
});
You can store additional data in your marker just by adding new fields like this:
var marker = new google.maps.Marker(
{
map : map,
position : point,
title : 'Click to view details',
icon : icon.icon,
shadow : icon.shadow,
myVariable1 : "some data from xml",
myVariable2 : "some other data"
});
Then all you have to do is register onClick event for the marker and put it's data into the form.
google.maps.event.addListener(marker, "click", function()
{
alert("Associated data: " + this.myVariable1 + ", " + myVariable2);
});
// Edit:
Obviously the code above only shows how to retrieve data from the marker - it was just an example. Putting your data from JavaScript into the form is a 2 step process. The first thing you have to do is to give every field you want to fill an unique id via "id" attribute. You've already done it. Then all you have to do is put following code in the onClick event (instead of alert() in the sample above):
document.getElementById('formdateoftrip').value = this.formdateoftrip;
// repeat it for other fields here
Good luck ;)
// Another edit:
I didn't notice you've put google.maps.event.addListener in wrong place. The reason it works for only one marker is you've put it outside your "for" loop which creates the markers. It has to be inside, right after the "map.fitBounds(bounds);" but before "}", so move it one line up.
The second problem lies in passing the data in the marker. If you want to reference variables, you can't put them in quotes. You use quotes to write strings.
Replace:
formdateoftrip: "dateoftrip",
formfindcategory: "findcategory",
...
Into:
formdateoftrip: dateoftrip,
formfindcategory: findcategory,
// fix the others below too

Categories