Send and retrieve data from web page in the background

Ajax (Asynchronous JavaScript and XML) is a technique on the client-side used to create asynchronous Web applications. With Ajax, Web applications can send data to, and retrieve data from, a server asynchronously (in the background) through JavaScript without interfering with the display and behavior of the existing page. Data can be retrieved using the XMLHttpRequest object.

Ajax request Example

Here is an example of a simple Ajax request using the GET method, written in JavaScript.


// This is the server-side script

// Set the content type
header('Content-Type: text/plain');

// Send the data back
echo "This is the returned text.";



<script type="text/javascript">
//Provide the XMLHttpRequest constructor for Internet Explorer 5.x-6.x:
if (typeof XMLHttpRequest === "undefined") {
  XMLHttpRequest = function () {
    try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); }
    catch (e) {}
    try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
    catch (e) {}
    try { return new ActiveXObject("Microsoft.XMLHTTP"); }
    catch (e) {}
    throw new Error("This browser does not support XMLHttpRequest.");

function doCall(){
  // Initialize the Ajax request
  var xhr = new XMLHttpRequest();
  xhr.open('get', 'send-ajax-data.php');

  // Track the state changes of the request
  xhr.onreadystatechange = function(){
    // Ready state 4 means the request is done
    if(xhr.readyState === 4){
      // 200 is a successful return
      if(xhr.status === 200){
        alert(xhr.responseText); // 'This is the returned text.'
        alert('Error: '+xhr.status); // An error occurred during the request

  // Send the request to send-ajax-data.php

  <input type="button" id="btn" value="Get Data" onclick="doCall()">

To see the demo page in action click here

jQuery example

This example uses the popular JavaScript library jQuery, to do the same thing as the example above.


	<title>jQuery.get() example</title>
	<script type="text/javascript" src="http://code.jquery.com/jquery-1.7.1.min.js"></script>

<script type="text/javascript">
function doCall(){
	$.get('send-ajax-data.php', function(data) {

<input type="button" id="btn" value="Get Data" onclick="doCall()">

To see the demo page in action click here

Why can't we use Ajax outside our domain?

If you try use ajax outside your domain, you will probably get this error message:

The reason you get this error message is because of the Same-origin policy. The policy permits scripts running on pages originating from the same site to access each other's data with no specific restrictions, but prevents scripts access to data that is stored on a different domain.

This could be a problem if you are trying to access publicly hosted data, but there are ways round it.

Here is the list of methods:

  • Implement CORS (Cross-Origin Resource Sharing)
  • Use JSONP (JSON Padding)
  • Use postMessage method
  • Setting up a local proxy

Cross-Domain AJAX Request methods

CORS (Cross-Origin Resource Sharing)

CORS is a mechanism that allows resources on a web page to be requested from another domain outside the domain the resource originated from. In particular, JavaScript's AJAX calls can use the XMLHttpRequest mechanism. Such "cross-domain" requests would otherwise be forbidden by web browsers, per the same origin security policy. CORS defines a way in which the browser and the server can interact to determine whether or not to allow the cross-origin request. It is more useful than only allowing same-origin requests, but it is more secure than simply allowing all such cross-origin requests.

CORS is a W3C recommendation and supported by all major browsers. It makes use of HTTP headers to help browser decide if a cross-domain AJAX request is secure. Basically, when you make a CORS request, browser adds Origin header with the current domain value.

For example:
Origin: http://www.ajax-cross-origin.com

The server, where the script makes its' CORS request, checks if this domain is allowed and sends response with Access-Control-Allow-Origin response header. Upon receiving, browser checks if the header is present and has the current domain value. If domains match, browser carries on with AJAX request, if not throws an error.

Access-Control-Allow-Origin: http://www.ajax-cross-origin.com

To allow access from all domains, a server can send the following response header:

Access-Control-Allow-Origin: *

To make a CORS request you simply use XMLHttpRequest in Firefox 3.5+, Safari 4+ & Chrome and XDomainRequest object in IE8+. When using XMLHttpRequest object, if the browser sees that you are trying to make a cross-domain request it will seamlessly trigger CORS behaviour.

Here is a javascript function that helps you create a cross browser CORS object:

function createCORSRequest(method, url){
  var xhr = new XMLHttpRequest();
  if ("withCredentials" in xhr){
    // XHR has 'withCredentials' property only if it supports CORS
    xhr.open(method, url, true);
  } else if (typeof XDomainRequest != "undefined"){ // if IE use XDR
    xhr = new XDomainRequest();
    xhr.open(method, url);
  } else {
    xhr = null;
  return xhr;

var request = createCORSRequest( "get", "http://www.google.com" );
if ( request ){
  // Define a callback function
  request.onload = function(){};
  // Send request

JSONP (JSON Padding)

JSONP or "JSON with padding" is a communication technique used in JavaScript programs running in web browsers to request data from a server in a different domain, something prohibited by typical web browsers because of the same-origin policy. JSONP takes advantage of the fact that browsers do not enforce the same-origin policy on <script> tags.

Because of the same origin policy, we can not make cross domain AJAX requests, but we can have <script> tags that load javascript files from other domains. JSONP uses this exception in order to make cross domain requests by dynamically creating a <script> tag with necessary URL.

Here is how it works. Server wraps data, usually in JSON format, in a function call. Upon loading the script, browser calls that function and passes loaded data. This implies the third party server knows the local javascript function name, but for obvious reasons that is not practical. The workaround is to pass the function name as a parameter to the request URL.

Note that for JSONP to work, a server must know how to reply with JSONP-formatted results.

Here an HTML <script> element specifies for its src attribute a URL that returns JSON:
<script type="text/javascript" src="http://www.example.com/path/getdata"></script>

The browser will, in order, download the script file, evaluate its contents, interpret the raw JSON data as a block, and throw a syntax error. Even if the data were interpreted as a JavaScript object literal, it could not be accessed by JavaScript running in the browser, since without a variable assignment object literals are inaccessible.

In the JSONP usage pattern, the URL request pointed to by the <script>'s src attribute returns JSON data, with a function call wrapped around it. In this way, a function that's already defined in the JavaScript environment can manipulate the JSON data. A JSONP payload might look like this:

functionCall({"Name": "Foo", "Id": 1234, "Rank": 7});

jQuery has built in support for JSONP requests in it's AJAX methods. To trigger a JSONP request you need to add callback_name=? string at the end of the URL. Here is an example using jQuery.

$.getJSON( url+"?callback=?", function( data ){
  console.log( data.title ); // Logs "jQuery Howto"

// OR using $.ajax()
  type:     "GET",
  url:      url,
  dataType: "jsonp",
  success: function(data){

postMessage method

window.postMessage method is part of HTML5 introductions. It allows communication between window frames without being subject to same origin policy. Using postMessage() one can trigger a message event with attached data on another window, even if the window has different domain, port or a protocol. The frame where the event is triggered must add an event listener in order to be able to respond.

Let's see an example. Assume, we are on http://example.com (1) website and would like to make a request to http://example2.net (2) domain. We first must obtain a reference to (2) window. This can be either iframe.contentWindow, window.open, or window.frames[]. For our case it's best to create a hidden iframe element and send messages to it. Here is how it looks.

// Create an iframe element
$('<iframe />', { id: 'myFrame', src: 'http://example2.net' }).appendTo('body');

// Get reference to the iframe element
var iframe = $('#myFrame').get(0);

// Send message with {some: "data"} data
iframe.postMessage( {some: 'data'}, 'http://example2.net');

The first argument is the data to be sent, the second is the URL of the current document. If this value is different from document.domain at the time when message is sent, browser will do nothing and silently ignore it. This is done for security reasons, since the frame's URL may change.

The page on server (2) must have an html content with a "message" event listener function. Let's use jQuery to do just that:

      $(window).on("message", function( event ){
        // We must check event.origin, because anyone can
        // trigger event. Unless, you are public data provider.
        if (event.origin !== "http://example.com") return;

        // Now let's send the (1) window data
        event.source.postMessage({name: "Someone", avatar: "url.jpg"}, event.origin);

In order to receive the data sent from server (2), we must add another event listener on page (1). Let's update our previous code.

var iframe = $('#myFrame').get(0);
iframe.postMessage( {some: 'data'}, 'http://example.com');

$(window).on("message", function( event ){
  if (event.origin !== "http://example2.net") return;
  console.log( event.data ); // Logs {name: "Someone", avatar: "url.jpg"}

Requirements & Notes

This method is relatively new and it is not used by that many services yet. All latest major browsers support it. However, IE8 & IE9 support only messaging between <frame> and <iframe>'s. IE10 supports messaging between windows, but only through MessageChannel's.

Setup local proxy

This method overcomes same origin policy by proxying content on another domain through itself. Thus making cross-domain issue irrelevant. To use this method you will either a) setup your server as a reverse proxy to fetch content from another server or b) write a script that would do that.

This cross domain querying solution works because you actually loading content from your own domain. You request the URL and the proxy script on your server loads the content and passes it over to you.

Here is a sample PHP proxy to get RSS feed from FeedBurner.

// Set your return content type
header('Content-type: application/xml');

// Website url to open
$url = 'http://feeds.feedburner.com/jQueryHowto';

// Get that website's content
$handle = fopen($url, "r");

// If there is something, read and return
if ($handle) {
    while (!feof($handle)) {
        $buffer = fgets($handle, 4096);
        echo $buffer;

Named the file proxy.php and make AJAX request to this URL. Here is a jQuery code example:

$("#rssFeeds").load("path/to/proxy.php", function(){
  // Some callback functions

AJAX Cross Origin - jQuery plugin

What is this plugin?

AJAX Cross Origin is a jQuery plugin to allow Cross Origin AJAX requests. This plugin use a combination of two Cross-Domain AJAX Request methods:

  • Use JSONP (JSON Padding)
  • Setting up a proxy

Code example

Add <script> tag:

<script type="text/javascript" src="js/jquery.ajax-cross-origin.min.js"></script>

Use jQuery.ajax():

  crossOrigin: true,
  //proxy: "http://www.domain.com/path/proxy.php" -> to overide default proxy
  url: url,
  success: function(data) {

Use jQuery.getJSON():

  crossOrigin: true

$.getJSON(url, null, function(data) {
  $( '#test' ).html(data);

Note: the only change from regular jQuery.ajax() call is the option: crossOrigin: true

How does it works?

The AJAX Cross Origin plugin use Google Apps Script as a proxy jSON getter where jSONP is not implemented. When you set the crossOrigin option to true, the plugin replace the original url with the Google Apps Script address and send it as encoded url parameter. The Google Apps Script use Google Servers resources to get the remote data, and return it back to the client as JSONP.

Note: Google limits the use of Google Apps Script per day, to bypass this limitation set the proxy option to alternative proxy.


$url = (isset($_GET['url'])) ? $_GET['url'] : false;
if(!$url) exit;

$referer = (isset($_SERVER['HTTP_REFERER'])) ? strtolower($_SERVER['HTTP_REFERER']) : false;
$is_allowed = $referer && strpos($referer, strtolower($_SERVER['SERVER_NAME'])) !== false;

$string = ($is_allowed) ? utf8_encode(file_get_contents($url)) : 'You are not allowed to use this proxy!';
$json = json_encode($string);
$callback = (isset($_GET['callback'])) ? $_GET['callback'] : false;
	$jsonp = "$callback($json)";
	header('Content-Type: application/javascript');
	echo $jsonp;
echo $json;

To see the demo page in action click here