Let’s work together

Feel free to send me an email at [email protected]

Research Campus 18
3500 Hasselt
Belgium

Facebox and remote ajax pages solution


Facebox and remote ajax pages solution

While facebox allows you to load remote pages via ajax, it doesn’t allow you to load ‘real remote’ pages from a different domain due to cross-domain policy. This is where jsonp comes in place.

Here’s a fix for facebox (current version 1.3).
Open up facebox.js and search for the ‘fillFaceboxFromAjax’ function. Now replace

$.get(href, function(data) { $.facebox.reveal(data, klass) })

with

$.ajax({
   url: href,
   dataType: 'jsonp',
   error: function(xhr, status, error) {
      alert(error);
   },
   success: jsonpCallback
});

And add a callback function:

function jsonpCallback(response){
   $.facebox.reveal(response.data, '');
}

Now this will only work if you also modify the remote file you’re calling. Make sure it will look something like this:

header('content-type: application/json; charset=utf-8');
$data = array(
   'data' => $generatedoutput,
);
$json = json_encode($data);
 
echo isset($_GET['callback']) ? "{$_GET['callback']}($json)" : $json;

Where $generatedoutput is your actual data (in this case I use ob_start and ob_get_contents for ease).
$_GET[‘callback’] is a parameter which is added automaticly by jquery. Read their docs for more info: http://api.jquery.com/jQuery.ajax/