Search code examples
javascriptphpajaxjsonjsonp

How to display pure HTML using JSONP


We are trying to avoid iframe and instead use javascript, jquery, jsonp and php based web widgets for our displaying content from our cross-domain html site. We want to display the full page as-is within the widget but from all the tutorials we read, its mentioned that we need to provide JSON datatype in order for cross-domain JSONP to work.

Here's what we tried -

Main JS

function render() {
  jQuery.getJSON(serverFQDN + '/widget.php?callback=?', {
  install_url: window.location.href
  }, serverResponse);
}

function serverResponse(data) {    
  jQuery(container).html(data.html);
}

Widget.php

<?php echo $_GET['callback'] ?>({
   "html": "<?php echo 'hello'; ?>"
});

We are able to display simple html entities like -

<?php   echo $_GET['callback'] ?>({"html": "<li>TEST</li>"

});

But not the full page i.e.

<?php
$url = "http://localhost/page.html";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, TRUE);
$output = curl_exec($curl);
curl_close($curl);
$output = json_encode($output);
echo $_GET['callback'] ?>({"html": "<?php echo $output; ?>"

});


Solution

  • You should use cURL or Firebug to check, but I think you are double-JSON-encoding your HTML.

    It's also not clear why you write:

    echo $_GET['callback'] ?>({"html": "<?php echo $output; ?>" });
    

    instead of

    echo $_GET['callback'] ?>({"html": $output });
    

    EDIT: Never mind, I have it. You are JSON-encoding just to Javascript-encode -- but you have an extra set of quotation marks!

    if $output is "<li>TEST</li>", then the file you are creating is

     jsonpCallback({"html" : ""<li>TEST</li>""});
    

    Uh, I think. Like I said, use cURL or Firebug to check the actual output.