In my case the same origin policy problem came up because I needed to make our website content available on a foreign website by using the Reverse Proxy technique. Which means that another website grabs our content and includes it into theirs. So for the users it looks like the content comes native from the foreign website.

The thing which made it a problem was, that we use a lot of “AJAX/AJAH” requests to process  form data etc.

Now if our native domain is native.com, the partner domain is partner.com (which includes our content) but the AJAX resource is still native.com the access would be forbidden by the same origin policy.

For instance if you observe such a XHR with Firebug, you’ll get a 200 Status, but the response body is empty.

If you google for a solution for this problem you’ll stumble across the buzz word Cross-origin resource sharing (CORS). But this technique just works for recent browsers like IE9+ etc.

Another way to solve the problem is the usage of the script-tag which allows cross-origin access and works with almost every common browser.

So lets work out the solution – by the way I use the jQuery framework -

Instead of catching the AJAX data with

    $.get(ajaxurl, function(data) {
      $('#resultsContainer').html(data);
    });

you need to get the data by adding a new script tag with the ajaxurl:
(I avoid to explain the whole solution path, it would go beyond the scope)

    if($('#ajaxScript').length!=0)
    {
      $('#ajaxScript').remove();
    }

    // Build temporary script tag to get AJAX results
    var scriptUrl             =  ajaxurl+'&useAsJsFunction=1';
    var script                = document.createElement( 'script' );
    script.type               = 'text/javascript';
    script.src                = scriptUrl;
    script.id                 = 'ajaxScript';

    if (script.addEventListener) // for normal browsers
    {
      script.addEventListener('load', function(){
        setAjaxData();
      }, false);
    }
    else // for old IEs
    {
      script.onreadystatechange = function(){
        if (script.readyState in {loaded: 1, complete: 1}) {
          script.onreadystatechange = null;
          setAjaxData();
        }
      };
    }

    document.body.appendChild(script);
    $(script).remove();

    function setAjaxData()
    {
      var ajaxData = getAjaxDataString();
      $('#resultsContainer').html(ajaxData);

      // Clean up the objects:
      $(ajaxData).remove();
    }

Explaination:

1. I enhanced the old ajaxurl with the parameter “&useAsJsFunction=1″. So the script behind the URL will build a javascript function body around the HTML data:

<?php if($useAsJsFunction): ?>
  function getAjaxDataString()
  {
    var data = '<?php echo str_replace(array("\r\n", "\r", "\n"), "", trim($content)); ?>';
    return data;
  }

<?php else: ?>

<?php echo $content; ?>

<?php endif; ?>

2. I set the ID attribute to the script tag for an easy later access to remove it from the DOM after I get the data. Because or otherwise every AJAX call will enhance a new script tag to the DOM.

3. The browser needs a while to load the foreign script containing the getAjaxDataString()-function which returns the ajax data. So I tried a lot of different ways with the setTimeout function etc. But I found the best solution to this async problem on phpied.com (thx a lot for your post). Instead of setting up an arbitary timeout it’s better to use the event handler when the script is loaded (onreadystatechange respectively onload).

4. getAjaxDataString(): I needed to remove the linebreaks etc. from the HTML string to avoid JS syntax errors. The HTML string inside of $content has no additional escaping stuff. But this would be different if you use JS code inside the returning HTML string!

5. document.body.appendChild(script) appends the script tag to the DOM. There are different ways to add it, but adding it to the body was the most readable way for later code reviews. First I used the head-tag as parent, but this caused problems with IE8 and older browsers.

6. $(script).remove() and $(ajaxdata).remove() are just to release the memory of these sometimes big objects, because they’re created more the once during a session.

 

Your’re welcome to post comments or improvements to my explanations.

 

Links:

Edit:

  • I don’t know why, but it’s funny that this solution seems to be faster than the jQuery XHR.
  • It does not work with Opera.