简体   繁体   中英

JS returning the wrong output PHP/XML file

I am trying to build a simple web 'app' where I will have a map (using the google maps api) and a few links below it as a 'filter'. I want to be filtering the data by type (ie: bar or restaurant).

Basically the map.html page uses javascript that picks up the XML which is generated by a PHP script.

here is the following code:

map.hmtl:

<!doctype html>
<html>
<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.googleapis.com/maps/api/js?key=AIzaSyASO80RjNn2d_Jjy9vdNHA5E3tfmALkWXw&sensor=false"></script>
    <script type="text/javascript">

        //<![CDATA[

        var customIcons = {
            restaurant: {
                icon: 'http://labs.google.com/ridefinder/images/mm_20_blue.png',
                shadow: 'http://labs.google.com/ridefinder/images/mm_20_shadow.png'
            },
            bar: {
                icon: 'http://labs.google.com/ridefinder/images/mm_20_red.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(47.6145, -122.3418),
                zoom: 13,
                mapTypeId: 'roadmap',
                disableDefaultUI: true
            });
            var infoWindow = new google.maps.InfoWindow;

            // Change this depending on the name of your PHP file
            downloadUrl("genxml3.php", 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 + "<br />" + type;
                    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>
</head>
<body onload="load()">
    <div id="map" style="width: 900px; height: 750px;"></div>
    <ul>
        <a href="#">Restaurant</a>
    </ul>
</body>
</html>

genxml3.php:

<?php  

require("dbinfo.php"); 

// Start XML file, create parent node

$dom = new DOMDocument("1.0");
$node = $dom->createElement("map");
$parnode = $dom->appendChild($node); 

// Opens a connection to a MySQL server

$connection=mysql_connect('localhost', $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
// Checks for the 'GET' variable, if there isn't, run normal XML script,
// if there is, get the restriction/filter and query from the database 
// with the filter

if (!empty($_GET)) {    
    $filter = $_GET['f'];
    $query = "SELECT * FROM markers WHERE type = '$filter'";
} else {
    $query = "SELECT * FROM markers WHERE 1";
}

$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("name",$row['name']);
  $newnode->setAttribute("address", $row['address']);  
  $newnode->setAttribute("lat", $row['lat']);  
  $newnode->setAttribute("lng", $row['lng']);   
  $newnode->setAttribute("type", $row['type']);
} 

echo $dom->saveXML();

?>

The PHP script generates the following XML code:

<map> 
    <marker name="Pan Africa Market changed" address="1521 1st Ave, Seattle, WA"     lat="47.6089" lng="-122.34" type="restaurant"/> 
    <marker name="Buddha Thai & Bar" address="2222 2nd Ave, Seattle, WA" lat="47.6136" lng="-122.344" type="bar"/> 
    <marker name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.6246" lng="-122.356" type="restaurant"/> 
    <marker name="Ipanema Grill" address="1225 1st Ave, Seattle, WA" lat="47.6064" lng="-122.338" type="restaurant"/> 
    <marker name="Sake House" address="2230 1st Ave, Seattle, WA" lat="47.6128" lng="-122.346" type="bar"/> 
    <marker name="Crab Pot" address="1301 Alaskan Way, Seattle, WA" lat="47.606" lng="-122.34" type="restaurant"/> 
    <marker name="Mama's Mexican Kitchen" address="2234 2nd Ave, Seattle, WA" lat="47.614" lng="-122.345" type="bar"/> 
    <marker name="Wingdome" address="1416 E Olive Way, Seattle, WA" lat="47.6172" lng="-122.327" type="bar"/> 
    <marker name="Piroshky Piroshky" address="1908 Pike pl, Seattle, WA" lat="47.6101" lng="-122.343" type="restaurant"/> 
</map>

and when I force a "get" variable in the nav bar (ie: genxml3.php?f=restaurant) the following XML code is outputed:

<map>    
    <marker name="Pan Africa Market changed" address="1521 1st Ave, Seattle, WA" lat="47.6089" lng="-122.34" type="restaurant"/>
    <marker name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.6246" lng="-122.356" type="restaurant"/>
    <marker name="Ipanema Grill" address="1225 1st Ave, Seattle, WA" lat="47.6064" lng="-122.338" type="restaurant"/>
    <marker name="Crab Pot" address="1301 Alaskan Way, Seattle, WA" lat="47.606" lng="-122.34" type="restaurant"/>
    <marker name="Piroshky Piroshky" address="1908 Pike pl, Seattle, WA" lat="47.6101" lng="-122.343" type="restaurant"/>    
</map>

So I know the logic in the PHP script works, because it filters the code needed. So if I put in "f=restaurant" only the markers with type "restaurant" show, and the same if I use "f=bar".

But the JavaScript still only uses the first XML code. How can I get the JavaScript code to use the second XML code (the one with the filter applied).

So what I am now looking for is a way to get the JavaScript code to run using the new XML code when a link in the map.html file is pressed?

You could apply the GET param on the map.html and process it with Javascript to your genxml3.php (map.html?f=restaurant ---> genxml3.php?f=restaurant).

To do this you define your links:

<a href="map.html?f=restaurant">Restaurant</a>
<a href="map.html?f=bar">Bar</a>

Then you resolve the GET parameter (if you're expecting only this one) via JS or jQuery:

var param = location.search;

Now you just do your usual load() when the page refreshes where you call downloadUrl() and add the part that was behind the map.html

downloadUrl("genxml3.php" + param, function(data) {

This is very simple and not a nice solution as there is no check about the params at all, but that's your part, it depends on your requirements.

If you don't want to refresh the page at all then you could assign a function to your links that are given a parameter (the filter name):

<a href="javascript:setFilter('restaurant');" title="">Restaurant</a>

You could also use jQuery and assign an event to all links and read out their innerHTML (the value). I am not sure if I understand your issue right, hope I could help.

WELL... your XML (the second marker node, name attribute) lacks of a syntax error: the & ampersand has to be escaped using the entity &amp; .

Actually PHP should do that automatically, do you use an older version?

As said in an answer to PHP - Is htmlentities() sufficient for creating xml-safe values? , change the PHP to

// 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("name", htmlspecialchars($row['name']));
  $newnode->setAttribute("address", htmlspecialchars($row['address']));  
  $newnode->setAttribute("lat", htmlspecialchars($row['lat']));  
  $newnode->setAttribute("lng", htmlspecialchars($row['lng']));   
  $newnode->setAttribute("type", htmlspecialchars($row['type']));
}

and give it a try...

The XML output should now look like

<map> 
<marker name="Pan Africa Market changed" address="1521 1st Ave, Seattle, WA"     lat="47.6089" lng="-122.34" type="restaurant"/> 
<marker name="Buddha Thai &amp; Bar" address="2222 2nd Ave, Seattle, WA" lat="47.6136" lng="-122.344" type="bar"/> 
<marker name="The Melting Pot" address="14 Mercer St, Seattle, WA" lat="47.6246" lng="-122.356" type="restaurant"/> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM