How do I pass JavaScript variables via FancyBox?

I’m attempting to pass JavaScript variables via FancyBox, so that I can access them in the window that appears. So far, I have the following code:


var s;
var e;
var fancyboxdata = new Array();
$(function(){
    $( '#post_code' ).blur(function(){
        s = $( '#post_code' ).val();
    });
});
function map_routes(e){
    if ((s.length !== 0) && (e.length !== 0)) {
        document.getElementById('map_routes_button').style.visibility="visible";
        fancyboxdata[s] = s;
        fancyboxdata[e] = e;
    } else {
        document.getElementById('map_routes_button').style.visibility="hidden";
    }
}
...


$(document).ready(function() {
    $("a.iframe_maps").fancybox({
        ajax: {
            type: "POST",
            data: fancyboxdata
        },
        'hideOnContentClick': true,
        'height': 600,
        'padding': 0,
        'width': 700, 
        'type': 'iframe'
    });
});

At this stage, I know the fancyboxdata array contains data, but I’m unsure about the Ajax parameter in the FancyBox function, which is supposed to pass the array variable.

In the window that appears, I have:

<?php

print_r($_POST);

echo $_POST['s'];

?>
<script>
    (function() {
        alert(fancyboxdata[s]);
    })();
</script>

I’ve tried: print_r($_POST), $phpVar, $_POST[“phpVar”], and $_POST[“phpVar”], bur nothing appears, other than empty arrays and errors in the debugger.

The error is just an explanation that the fancyboxdata array variable can’t be found. And in PHP:

<p>Severity: Notice</p> <p>Message: Undefined index: s</p> <p>Filename: bookings/maps.php</p> <p>Line Number: 5</p>

And just so you know, I’m building this within CodeIgniter.

Any ideas?

It seems that you have attached FB to an anchor tag with a class of “iframe_maps”

$("a.iframe_maps").fancybox({

Could you post this little snippet of HTML.

It probably looks something like:

<a class="fancybox fancybox.iframe" href="...">Open iFrame</a>

Pullo (or Dave), here’s the code for the button:

<div id="map_routes_button">
    <div id="button-link"><a class="iframe_maps button-link" href="#" title="Plan your journey">Journey Planner</a></div>
</div>
<script type="text/javascript">
    document.getElementById('map_routes_button').style.visibility="hidden";
</script>

Launching the FancyBox window is not the problem; that part works fine.

Anticipating your next suggestion, sending the post codes as URL parameters isn’t a viable solution.

Howdy Forbes,

The problem is that you are never going to be able to send a POST request using just an <a> element.
In its current state your code is always going to be firing a GET request.

Why is it not an option to pass the data as a URL parameter?
This would work as expected.

I’ve tried POST and GET and neither contain any data.

Because I’m using JavaScript, which is unreliable, and it would involve sending a GET request to a page, which wouldn’t work in the context of the framework.

I’m open to any recommendations of code alterations, to make this work.

I am by no means an expert in JavaScript, Ajax, or jQuery!

Hi,

GET would work like this:

var myVar ="something";

$("#send").click(function(e){
  e.preventDefault();
  var Href = 'iframe.php?name=' + myVar;
  $.fancybox.open({
    href: Href,
    type: 'iframe'
  });
});
<a class="iframe_maps button-link" href="" title="Plan your journey" id="send">Journey Planner</a>

However, I have no experience of the framework you are using, so maybe this approach wouldn’t work for you.

Another idea would be to construct your content in your main document (you could fetch whatever you need via AJAX), then pass everything to FancyBox using its content parameter.

I was just playing around with the second possibility I suggested and got quite nice results doing the following:

index.html

<!DOCTYPE html>
<html>
  <head>
    <title>fancyBox - Fancy jQuery Lightbox Alternative | Demonstration</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.1.4"></script>
    <link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.1.4" media="screen" />
  </head>

  <body>
    <a href="" id="send" class="fancybox" >Off we go</a>

    <script type="text/javascript">
      $(document).ready(function() {
        var name = "Pullo"
				
        $("#send").click(function() {
          $.fancybox.showLoading();
          $.ajax({
            type : "POST",
            cache : false,
            url : "test.php",
            data  : 'myData=' + name,
            success : function(data) {
              $.fancybox(data);
            }
          });
          return false;
        });
      });
    </script>
  </body>
</html>

test.php

<?php
  $m = ($_POST['myData']);
  echo "Hello there, $m!";
?>

This way, you submit everything to test.php via AJAX.
In test.php you have access to the $_POST super-global in all its glory.
You can then manipulate your data as you wish, then pipe it back to display in FancyBox.

Simples!

Okay, I’m nearly there. But there are a few problems:

  1. I can’t remove the loading icon, even when I delete the $.fancybox.showLoading(); attribute;
  2. I can only send one parameter, and data: ‘s=’ + s + ‘&’ + ‘e=’ + e doesn’t appear to work, in that only ‘s’ is carried forward, while ‘e’ appears to be undefined, even though data is present prior to submission;
  3. also, Fancy Box only works once, and no subsequent attempts result in a window.

Pullo, thanks for the help so far.

Good evening,

To your points:

Are you sure?
This does it for me.
Maybe you have extra code somewhere that is causing this?

I find this surprising.
This works for me:

data  : 'firstName=' + firstName + '&lastName=' + lastName

I’ve updated my script at the bottom of this post for you totry it out.

Again, I find this surprising.
I can call FB as many times as I like (see the example).

index.html

<!DOCTYPE html>
<html>
  <head>
    <!--http://www.sitepoint.com/forums/showthread.php?969091-How-do-I-pass-JavaScript-variables-via-FancyBox-->
    <title>fancyBox - Fancy jQuery Lightbox Alternative | Demonstration</title>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <script type="text/javascript" src="http://code.jquery.com/jquery-latest.min.js"></script>
    <script type="text/javascript" src="http://fancyapps.com/fancybox/source/jquery.fancybox.pack.js?v=2.1.4"></script>
    <link rel="stylesheet" type="text/css" href="http://fancyapps.com/fancybox/source/jquery.fancybox.css?v=2.1.4" media="screen" />
  </head>
  
  <body>
    <p>Click here to <a href="" class="send fancybox" data-first="King" data-last="Pullo">Greet King Pullo</a></p>
    <p>Click here to <a href="" class="send fancybox" data-first="Pullo" data-last="the Mightier">Greet Pullo the Mightier</a></p>
    
    <script type="text/javascript">
      $(document).ready(function() {
        
        $(".send").click(function() {
          firstName = $(this).attr("data-first");
          lastName = $(this).attr("data-last");
          
          $.fancybox.showLoading();
          $.ajax({
            type : "POST",
            cache : false,
            url : "test.php",
            data  : 'firstName=' + firstName + '&lastName=' + lastName,
            success : function(data) {
              $.fancybox(data);
            }
          });
          return false;
        });
      });
    </script>
  </body>
</html>

test.php

<?php 
$f = ($_POST['firstName']); 
$l = ($_POST['lastName']); 
echo "Hello there, $f $l!";
?>

If I was you, I’d take a second to run the example I provide and see if your issues persist.
If so, then there is a glitch in the Matrix, if not, then we have narrowed the problem down to your script.
Either way, i would be interested to know how you get on.

Okay, there’s an error somewhere in my code, which is responsible for ‘e’ not being passed along to FancyBox.

As for the loading graphic, I don’t have anything else on the page that would do that; your code introduced that feature, and it’s something I don’t use anywhere in the application.

Also, your code relies on the newer version of FancyBox, which essentially disables every instance that uses code specific to the earlier version — of which there are many throughout the application.

Fun and games!

Oh dear!

I rewrote my example to use FancyBox 1.3.4.
Does this work for you?

index.php:

<!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>FancyBox 1.3.4 | Demonstration</title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
    <script type="text/javascript" src="http://hibbard.eu/blog/pages/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
    <link rel="stylesheet" type="text/css" href="http://hibbard.eu/blog/pages/fancybox/jquery.fancybox-1.3.4.css" media="screen" />
  </head>
  <body>
    <p>Click here to <a href="test.php" class="send fancybox" data-first="King" data-last="Pullo">Greet King Pullo</a></p>
    <p>Click here to <a href="test.php" class="send fancybox" data-first="Pullo" data-last="the Mightier">Greet Pullo the Mightier</a></p>
    
    <script type="text/javascript">
      var firstName, lastName;
      
      $(".fancybox").click(function(e) {
        e.preventDefault();
        firstName = $(this).attr("data-first");
        lastName = $(this).attr("data-last");
        $.fancybox(this, {
          ajax : {
            type  : "POST",
            data  : 'firstName=' + firstName + '&lastName=' + lastName
          }
        });
      });
    </script>
  </body>
</html>

test.php:

<?php 
  $f = ($_POST['firstName']); 
  $l = ($_POST['lastName']); 
  echo "Hello there, $f $l!";
?>

Just to be clear, your examples work perfectly. It’s the integration with my application that’s causing the problems, especially with the error in my code.

If you don’t mind, I have to go, but I’ll be sure to try tomorrow.

Pullo, thanks again.

No probs :slight_smile:
It can be quite annoying when you’re looking for a solution to a complicated problem and you have to try and bring a stranger up to speed with your project.

Nonetheless, hopefully the last example I posted should help you implement the POST request correctly and route the response back to FancyBox.
Let me know how you got on.

Cheers

Pullo, what does your ‘e’ variable do? I ask because that’s the name of the variable I’m having problems with.

It represents the “click” event.
As, in this example, the page to display in FancyBox is hard-coded into the “href” (i.e. test.php) we need to prevent the browser following that link.
That’s what this line does:

e.preventDefault();

HTH

Okay, I Googled the preventDefault() function, so understand what that does.

However, I simply don’t know enough about JavaScript / jQuery (whatever it’s called) to fix the bug in my code, or how to implement your code and have it work (I can’t get Fancy Box to work reliably, other than using the code I’m using elsewhere, but won’t work here in this exercise).

Because of the time constraints, I may have to abandon this exercise, largely because I honestly don’t know what’s going on, and this needs to be maintainable in the future.

That’s a shame :frowning:

If you can post a link to a page where I can see all of this in action, I don’t mind taking a look.

Thanks for the kind offer. It’s a commercial application, which requires sign in details, so I’ll send you a private message with details for the development version.

Hi Forbes,

So I got it working.

This is what I did:

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

This line is invalid as you have two elements with the same id.
I changed it as follows:

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

Notice I also changed the file to which the AJAX post request is sent to “test.php”.
In test.php I just have <?php print_r($_POST); ?>

You have this JavaScript at the top of the document.

var s;
var e;
var fancyboxdata = new Array();
$(function(){
  $('#post_code').blur(function(){
    s = $('#post_code').val();
  });
});

function map_routes(e){
  if ((s.length !== 0) && (e.length !== 0)) {
    fancyboxdata[0] = s;
    fancyboxdata[1] = e;
    document.getElementById('map_routes_button').style.visibility="visible";
  } else {
    document.getElementById('map_routes_button').style.visibility="hidden";
  }
}

$("#button-link").click(function(event) {
  event.preventDefault();
  _s = fancyboxdata[0];
  _e = fancyboxdata[1];
  $.fancybox(this, {
    ajax: {
      type : "POST",
      data : 's=' + _s + '&e=' + _e
    }
  });
});

Move it to the bottom of your file and place it directly before the closing </body> tag.
This is also where the Google Analytics code should go (before the </body>, not after).

Change this:

$("#button-link").click(function(event) {

into this:

$("#button-link1").click(function(event) {

Now when I submit the form, I see:

Array ( [s] => HA9 OAA [e] => Postcode )

displayed in FancyBox.

Yay :slight_smile:

Pullo, thanks again. I’ll have a try later this evening and let you know how I get on.