Monday, May 3, 2010

Making Cross Domain jQuery AJAX Calls

Today's web browsers do not allow web pages to make cross-domain ajax calls. By this i mean that if you are at www.ajax.com and try to make an Ajax call ( an HTTP request using the XmlHttpRequest object) to www.other-domain.com the browser would not allow this to happen. Why? For security purposes that i cannot currently name.

However, at some point you get to a project where you're interfacing this third-party site that needs to talk to your main site, or some other similar situation where the only way you're going to get the data you need from point a to point b is with some javascript magic. Here is how to accomplish it:

How to get/post data using jQuery/javascript (JSONP)

The short answer: its not ajax at all, its JSONP. Yes, JSONP is not Ajax. I just learned this today. Like i said earlier, browsers do not allow XHR/Ajax cross-browser requests. JSONP avoids this by making a request for a script file-- no Ajax at all. Let me explain:

  1. Instead of accessing the XHR object, the browser first creates a new script tag to inject into the HTML DOM
  2. The script tag's URL is set to the URL you're looking to get/post(using HTTP GET) data to
  3. The script tag is injected into the page, causing...
  4. The request is sent to the server, even if its cross-domain
  5. The server returns the data in the form of a javascript function call
  6. The browser receives the data and executes the function call

jQuery code

//use a get to post a querystring value via HTTP GET to an asp.net webhandler
$.getJSON("http://www.example.com/get-post.ashx?var1=var1value&callback=?",function(data){
     //really no need to do anything here, we're just posting data
     //but this will output success
     alert(data.return);
});

asp.net generic handler/webhandler code

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace jsonp_test
{
    /// 
    /// Summary description for $codebehindclassname$
    /// 
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class get_post : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            string callback = "";
            try
            {
                if (!string.IsNullOrEmpty(context.Request["callback"]))
                {
                    if (!string.IsNullOrEmpty(context.Request["var1"]))
                        SaveData(context.Request["var1"]);
                    callback = context.Request["callback"];

                    context.Response.Write(callback + "({ \"return\": \"Success\" })");
                }
            }
            catch (Exception exc)
            {
                //hopefully this error doesnt contain any quotes... you know?
                context.Response.Write(callback + "({ \"return\": \"" + exc.Message + "\" })");
            }
        }

        private void SaveData(string value)
        {
            //do something with the var1 posted to us
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}

So what we effectively have here is the setup for asp.net cross domain ajax calls using jQuery

How to do cross-domain calls to others' servers: YQL

What if you need to do a get but don't have the ability to make the page its posting to return a JSONP response? Using YQL is a great way to achieve this.

YQL is a way to query the internet like it is a database. For example, one could easily run

select * from html where url="http://www.microsoft.com"

and recieve a JSONP return containing all of the site's HTML. You could also, do the following

select * from html where url="http://www.mircorosft.com?var1=var1value"

and HTTP GET values to the server. YQL does not allow this to happen on any area of any site that is blocked by the robots.txt file. Here's full example code:

//feel free to add querystring vars to this
var myurl="http://www.example.com/get-post.ashx?var1=var1value&callback=?";
//make the call to YQL 
$.getJSON("http://query.yahooapis.com/v1/public/yql?"+
                "q=select%20*%20from%20html%20where%20url%3D%22"+
                encodeURIComponent(myurl)+
                "%22&format=xml'&callback=?",
        function(data){
          if(data.results[0]){
            //this data.results[0] is the return object you work with, 
            //if you actually want to do something with the returned json
            alert(data.results[0]);
          } else {
            var errormsg = '

Error: could not load the page.

'; //output to firebug's console //use alert() for other browsers/setups conole.log(errormsg); } } );

No comments:

Post a Comment