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/

Freelance webdeveloper & Entreprenerd Specialized in developing, scaling and optimizing of succesful web applications, community websites and small/corporate business websites using technologies such as PHP 5, Laravel, HTML5, jQuery, .. Trying to find optimal Google love for every website. I'm always interested and open for new business opportunities.