How do I pass JavaScript variables via FancyBox?

Pullo, you’ve been an enormous help.

Okay, this is mostly working, except the close button on the Fancy Box doesn’t actually close it.

Howdy,

I took your code and swapped this:

<a class="fancybox button-link" id="button" href="http://yourdomain.com/bookings/maps/routes/5" title="Plan your journey">Journey Planner</a>

for this:

<a class="fancybox button-link" id="button" href="test.php" title="Plan your journey">Journey Planner</a>

and the problem went away (i.e. I could close FancyBox as expected).

Ergo, something on the page you are posting the data to is causing an error.
Is it possible for you to share the PHP code behind “bookings/maps/routes/5”?

I cannot debug this remotely, due to the fact that my browser will not let me make a cross domain AJAX call (for security reasons).

I’ve uploaded the most recent changes.

Firstly, “bookings/maps/routes/5” has to remain in place because that’s where the Google Maps data is generated.

Secondly, the error is “‘undefined’ is not an object (evaluating ‘f.width’)” which is triggering on a line that has no relevant code associated with it.

To help you, I need to have a look at “bookings/maps/routes/5”.
Is that possible at all?

Yes, once you’ve gone through the post code selection process (per the instructions I sent you), right-click the “Journey Planner” button and open it in a separate tab.

Obviously, the post code fields are going to be empty because the “POST” process won’t have run, but you’ll have complete access to the code.

Weirdly, the default map locations loads this way, but doesn’t via the usual means, which I suspect us due to the error.

Ok, I’ve done that, but that only leaves me with the option of viewing the source code.
Isn’t there some PHP code which generates that HTML?

PHP is minimal; I’m only using it to build the form, and initialise the post code values.

For the sake of completeness, here’s the code for the page in question:

<?php
	$attributes['route'] = array(
		'name' => 'form-route',
		'id' => 'form-route',
		'class' => 'form-route'
	);
?>
			<div class="box-modal">
				<h2>Route Planning</h2>
				<div id="map-container"><div id="map" class="map"></div></div>	
				<form action="/route" onSubmit="calcRoute(); return false;" id="form-route">
					<fieldset>
						<legend>Start</legend>
						<div class="column-left">
							<ol>
								<li>Choose your mode of transport</li>
								<li>Enter your address or post code</li>
							</ol>
							<ul id="transport">
								<li><img id="trans-car" src="<?php echo config_item('base_url'); ?>library/images/ui/transport/car.png" alt="Car" width="30" height="30" /></li>
								<li><img id="trans-bus" src="<?php echo config_item('base_url'); ?>library/images/ui/transport/bus.png" alt="Bus or Train" width="30" height="30" /></li>
							</ul>
							<script type="text/javascript">
								imgpath = '<?php echo config_item('base_url'); ?>library/images/ui/transport/';
								document.getElementById('trans-car').onclick = function() {
									trans = google.maps.DirectionsTravelMode.DRIVING;
									this.src = imgpath+'car2.png';
									if (document.getElementById('trans-bus').src == imgpath+'bus2.png') {
										document.getElementById('trans-bus').src = imgpath+'bus.png';
									}
								}
								document.getElementById('trans-bus').onclick = function() {
									trans = google.maps.DirectionsTravelMode.TRANSIT;
									this.src = imgpath+'bus2.png';
									if (document.getElementById('trans-car').src == imgpath+'car2.png') {
										document.getElementById('trans-car').src = imgpath+'car.png';
									}
								}
							</script>
							<dl>
								<dt><label for="route-start">Start</label></dt>
								<dd><input type="text" id="route-start" value=""></dd>
								<dt><label for="route-end">Destination</label></dt>
								<dd><input type="text" id="route-end" value=""></dd>
							</dl>
							<div id="button">
								<?php $button = array ('name' => 'submit', 'value' => 'Plan Route', 'class' => 'button'); echo form_submit($button); ?>
							</div> <!-- button -->
						</div> <!-- .column-left -->
						<div id="directions"></div>
						<div class="cleaner"></div>
					</fieldset>
				</form>
				<script type="text/javascript">
					document.getElementById('route-start').value = "<?php echo $_POST['s']; ?>";
					document.getElementById('route-end').value = "<?php echo $_POST['e']; ?>";
				</script>
			</div> <!-- box-modal -->
			<script type="text/javascript">
				$(document).ready(function() {
					initialize(); 
				});
				var la = '52.43564';
				var lo = '-1.64363';
				var venue = "To Book Limited";
				var trans = google.maps.DirectionsTravelMode.DRIVING;
				var directionDisplay;
				var directionsService = new google.maps.DirectionsService();
				function initialize() {
					var latlng = new google.maps.LatLng(la,lo);
					directionsDisplay = new google.maps.DirectionsRenderer();
					var myOptions = {
						zoom: 14,
						center: latlng,
						mapTypeId: google.maps.MapTypeId.ROADMAP,
						mapTypeControlOptions: {
							style: google.maps.MapTypeControlStyle.DEFAULT
						}
					};
					var map = new google.maps.Map(document.getElementById("map"),myOptions);
					directionsDisplay.setMap(map);
					directionsDisplay.setPanel(document.getElementById("directions"));
					var marker = new google.maps.Marker({
						position: latlng, 
						map: map,
						title: venue
					});
				}
				function calcRoute() {
					var start = document.getElementById("route-start").value;
					var end = document.getElementById("route-end").value;
					var request = {
						origin: start,
						destination: end,
						travelMode: trans
					};
					directionsService.route(request, function(response, status) {
						if (status == google.maps.DirectionsStatus.OK) {
							directionsDisplay.setDirections(response);
						} else {
							if (status == 'ZERO_RESULTS') {
								alert('No route could be found between the origin and destination.');
							} else if (status == 'UNKNOWN_ERROR') {
								alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
							} else if (status == 'REQUEST_DENIED') {
								alert('This webpage is not allowed to use the directions service.');
							} else if (status == 'OVER_QUERY_LIMIT') {
								alert('The webpage has gone over the requests limit in too short a period of time.');
							} else if (status == 'NOT_FOUND') {
								alert('At least one of the origin, destination, or waypoints could not be geocoded.');
							} else if (status == 'INVALID_REQUEST') {
								alert('The DirectionsRequest provided was invalid.');
							} else {
								alert("There was an unknown error in your request. Requeststatus: \
\
"+status);
							}
						}
					});
				}
			</script>

Sorted!
That helps a lot.
I’ve got to scoot out now, but I’ll have a look at this when I get back and I’ll post back later.

Ok, I’ve had a look at it.
In addition to the PHP code you posted you must be doing something like this:


<?php include (TEMPLATEPATH . 'header.php' ); ?>
...
The code you posted
...
<?php include (TEMPLATEPATH . 'footer.php' ); ?>

Remove both the header and footer includes. You don’t need them.
You can just have “bookings/maps/routes/5” return a lump of HTML to display in FancyBox.
As it is you are having “bookings/maps/routes/5” return a complete page (with JavaScript includes).
Including these JavaScripts in your page for a second time is causing things to break.

The application can’t function without the header and footer; they’re essential.

Where are you seeing a duplication of JavaScript?

I’m not suggesting that you move them from your main page, but they are not necessary for the PHP script sitting behind “bookings/maps/routes/5” which you want to display in the FancyBox (unless of course you want to load this page directly elsewhere in your app).

To see what I mean:
Select the post code (per the instructions you sent me), then right-click the “Journey Planner” button and open it in a separate tab.
Then look at the page source.

I see:

url: www.yourdomain/bookings/maps/routes/5

<!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" xml:lang="en" lang="en">
  <head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <title>Journey &raquo; Client Control Panel &mdash; To Book</title>
    <style rel="stylesheet" type="text/css">
      @import url("http://www.yourdomain/library/styles/styles.css");
    </style>
    <link rel="stylesheet" type="text/css" href="http://www.yourdomain/library/styles/anytime.css" />
    <link href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/themes/base/jquery-ui.css" rel="stylesheet" type="text/css"/>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5/jquery.min.js"></script>
    <script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
    <!-- Load ScrollTo -->
    <script type="text/javascript" src="http://flesler-plugins.googlecode.com/files/jquery.scrollTo-1.4.2-min.js"></script>
    <!-- Load LocalScroll -->
    <script type="text/javascript" src="http://flesler-plugins.googlecode.com/files/jquery.localscroll-1.2.7-min.js"></script>
    <script type="text/javascript" src="http://www.yourdomain/library/scripts/jquery.fancybox-1.3.4/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
    <script type="text/javascript" src="http://www.yourdomain/library/scripts/anytime.js"></script>
    <script type="text/javascript" src="http://maps.google.com/maps/api/js?sensor=false"></script>
  </head>
  <body>
    <div id="application-surround-modal">
      <div id="application-container-modal">
      <div class="box-modal">
        <h2>Route Planning</h2>

Whereas the PHP code you posted starts:

<?php
  $attributes['route'] = array(
    'name' => 'form-route',
    'id' => 'form-route',
    'class' => 'form-route'
  );
?>
<div class="box-modal">
  <h2>Route Planning</h2>
  <div id="map-container">
    <div id="map" class="map"></div>
  </div>

If I view the page source of www.yourdomain/bookings/maps/routes/5, copy the HTML from between the two <body> tags into “test.php” (so, minus the JS includes etc) and have that open in FancyBox, then everything works as expected.

I see what you mean, but it’s not possible to do that because of the framework.

I discovered, through testing, that some users can’t “see” Fancy Box, and the floating windows open as regular windows or tabs in their web browser. If I didn’t include the headers and footers, those windows and tabs wouldn’t function properly.

Also, I use the same principle throughout the entire application without any problems. I even use Google Maps in a Fancy Box elsewhere, with no errors.

I may need to send you additional sign-in details to see what I mean.

Does this mean that it’s the framework inserting the header and footer and you have no way to influence this in your code?
This would be unfortunate.

It’s not Google Maps that’s causing things to crash, I think it’s the fact that you are re-including jQuery and/or FancyBox (as you are getting errors which would point to this, such as “Uncaught TypeError: Property ‘undefined’ of object #<Object> is not a function”).

I’ve created a switch in the way the “views” (analogous to the include() and require() functions) so that the various links, scripts and styles can be controlled, and it appears to be working, although the default location still isn’t loading.

Slowly but surely, things are coming together.

Just to be clear, I use a Fancy Box to manage a location finder which uses Googles Maps. As far as I’m aware, there are no errors.

Having trimmed down the scripts, links, and styles to the bare minimum, I’ve found that the error relates to line 64 in the Fancy Box file:

$(document).ready(function() {

However, the edit file — which uses exactly the same code — does not have any similar error.

Currently when I look at the page, I see either just a bit of Google maps, or nothing (depending on which location I chose).
But, at least we’ve now made FancyBox behave as it should :slight_smile:

Could you post the complete PHP code from “bookings/maps/routes/5”, unless it hasn’t changed, in which case I’ll copy it from your previous post.

In addition to trimming the header, I added a few conditional statements to handle the lack of post codes, if the visitor opens the page in a window or tab:

<?php
    $attributes['route'] = array(
        'name' => 'form-route',
        'id' => 'form-route',
        'class' => 'form-route'
    );


[B]    if (!empty($_POST['s'])):
        $s = $_POST['s'];
    else:
        $s = '';
    endif;


    if (!empty($_POST['e'])):
        $e = $_POST['e'];
    else:
        $e = '';
    endif;[/B]


?>
            <div class="box-modal">
                <h2>Route Planning</h2>
                <div id="map-container"><div id="map" class="map"></div></div>    
                <form action="/route" onSubmit="calcRoute(); return false;" id="form-route">
                    <fieldset>
                        <legend>Start</legend>
                        <div class="column-left">
                            <ol>
                                <li>Choose your mode of transport</li>
                                <li>Enter your address or post code</li>
                            </ol>
                            <ul id="transport">
                                <li><img id="trans-car" src="<?php echo config_item('base_url'); ?>library/images/ui/transport/car.png" alt="Car" width="30" height="30" /></li>
                                <li><img id="trans-bus" src="<?php echo config_item('base_url'); ?>library/images/ui/transport/bus.png" alt="Bus or Train" width="30" height="30" /></li>
                            </ul>
                            <script type="text/javascript">
                                imgpath = '<?php echo config_item('base_url'); ?>library/images/ui/transport/';
                                document.getElementById('trans-car').onclick = function() {
                                    trans = google.maps.DirectionsTravelMode.DRIVING;
                                    this.src = imgpath+'car2.png';
                                    if (document.getElementById('trans-bus').src == imgpath+'bus2.png') {
                                        document.getElementById('trans-bus').src = imgpath+'bus.png';
                                    }
                                }
                                document.getElementById('trans-bus').onclick = function() {
                                    trans = google.maps.DirectionsTravelMode.TRANSIT;
                                    this.src = imgpath+'bus2.png';
                                    if (document.getElementById('trans-car').src == imgpath+'car2.png') {
                                        document.getElementById('trans-car').src = imgpath+'car.png';
                                    }
                                }
                            </script>
                            <dl>
                                <dt><label for="route-start">Start</label></dt>
                                <dd><input type="text" id="route-start" value=""></dd>
                                <dt><label for="route-end">Destination</label></dt>
                                <dd><input type="text" id="route-end" value=""></dd>
                            </dl>
                            <div id="button">
                                <?php $button = array ('name' => 'submit', 'value' => 'Plan Route', 'class' => 'button'); echo form_submit($button); ?>
                            </div> <!-- button -->
                        </div> <!-- .column-left -->
                        <div id="directions"></div>
                        <div class="cleaner"></div>
                    </fieldset>
                </form>
                <script type="text/javascript">
                    document.getElementById('route-start').value = "<?php echo [B]$s[/B]; ?>";
                    document.getElementById('route-end').value = "<?php echo [B]$e[/B]; ?>";
                </script>
            </div> <!-- box-modal -->
            <script type="text/javascript">
                $(document).ready(function() {
                    initialize(); 
                });
                var la = '52.43564';
                var lo = '-1.64363';
                var venue = "To Book Limited";
                var trans = google.maps.DirectionsTravelMode.DRIVING;
                var directionDisplay;
                var directionsService = new google.maps.DirectionsService();
                function initialize() {
                    var latlng = new google.maps.LatLng(la,lo);
                    directionsDisplay = new google.maps.DirectionsRenderer();
                    var myOptions = {
                        zoom: 14,
                        center: latlng,
                        mapTypeId: google.maps.MapTypeId.ROADMAP,
                        mapTypeControlOptions: {
                            style: google.maps.MapTypeControlStyle.DEFAULT
                        }
                    };
                    var map = new google.maps.Map(document.getElementById("map"),myOptions);
                    directionsDisplay.setMap(map);
                    directionsDisplay.setPanel(document.getElementById("directions"));
                    var marker = new google.maps.Marker({
                        position: latlng, 
                        map: map,
                        title: venue
                    });
                }
                function calcRoute() {
                    var start = document.getElementById("route-start").value;
                    var end = document.getElementById("route-end").value;
                    var request = {
                        origin: start,
                        destination: end,
                        travelMode: trans
                    };
                    directionsService.route(request, function(response, status) {
                        if (status == google.maps.DirectionsStatus.OK) {
                            directionsDisplay.setDirections(response);
                        } else {
                            if (status == 'ZERO_RESULTS') {
                                alert('No route could be found between the origin and destination.');
                            } else if (status == 'UNKNOWN_ERROR') {
                                alert('A directions request could not be processed due to a server error. The request may succeed if you try again.');
                            } else if (status == 'REQUEST_DENIED') {
                                alert('This webpage is not allowed to use the directions service.');
                            } else if (status == 'OVER_QUERY_LIMIT') {
                                alert('The webpage has gone over the requests limit in too short a period of time.');
                            } else if (status == 'NOT_FOUND') {
                                alert('At least one of the origin, destination, or waypoints could not be geocoded.');
                            } else if (status == 'INVALID_REQUEST') {
                                alert('The DirectionsRequest provided was invalid.');
                            } else {
                                alert("There was an unknown error in your request. Requeststatus: \
\
"+status);
                            }
                        }
                    });
                }
            </script>

I’ve copied that to “test.php” which is the file I am sending the AJAX request to locally (would be “bookings/maps/routes/5” for you).
However, when I go through the steps detailed previously (enter postcode etc), FancyBox opens and I see:

Route Planning
Start
Choose your mode of transport
Enter your address or post code

But no Google Maps (i.e. the map doesn’t display at all and I can’t reproduce your issue).

Is your framework adding anything else to the file?

When I do the same thing on the live site, then examine what pops up in FancyBox using Chrome’s Dev Tools, I see:

<meta http-equiv="content-type" content="text/html; charset=utf-8">
<title>Journey » Client Control Panel &#8212; To Book</title>
<style rel="stylesheet" type="text/css">
  @import url("http://www.yourdomain/library/styles/styles.css");
</style>
<div id="application-surround-modal">
<div id="application-container-modal">
			<div class="box-modal">
				<h2>Route Planning</h2>

all of which is missing from the PHP you posted.

I just need to be able to reproduce your error.

As I said earlier, I’ve stripped the header down, yet I see an error on line 64.

However, the error doesn’t happen on the location finder that I mentioned earlier.