•  

    Cross-Site Ajax

    Last week we ran into a problem trying to call a page with an XMLHttpRequest from one domain to another.

    The situation was odd. We weren’t trying to call another domain from our domain, we were trying to make a call to our domain from another domain. Within Salesforce’s CRM, there’s a component known as an SControl. This component is an HTML page with accompanying Javascript used to create a custom interface within Salesforce.

    After asking for various inputs, we wanted to send those to our own domain for processing, and spit back a response. Our first thought was to use a simple XMLHttpRequest to do the post. We use jQuery within that, and so it should have been as simple as:

    $.post(”url”, params, function(data){});

    Unfortunately, what I forgot was domain security. As I said above, this didn’t work at all.

    I found our solution at Kevin Yank’s blog with an entry about OSCON 2006. The basic idea is to dynamically insert a <script> tag to handle your cross site code. This works because script tags can load code from different domains.

    Our final solution looks something like this:

    <script src=”page?field1=value1&callback=functionName” type=”text/javascript”></script>

    What this does is makes a get request to “page” passing along the form variables that we previously wanted to post in the querystring. The page then returns something that looks like:

    functionName(’data you want to return’);

    The functionName just needs to be a function you write to handle whatever you’re expecting as a return from the page.

    Leave a Reply