Cross Domain Requests

In order to generate a rich web experience, it is not uncommon to make requests to servers in other domains. Unfortunately, JavaScript’s same origin policy prohibits you from making a request to a server in another domain. There are many ways to overcome this restriction like, using Jquery’s .ajax method, HTML5 CORS(Cross-Origin Resource Sharing) and JSONP.

JSONP is the simplest way to make a cross domain request. JSONP or “JSON with padding” is a technique that can be used to load JavaScript from a server in a different domain. JSONP takes advantage of the fact that JavaScript’s same origin policy doesn’t apply to the HTML <script> element.

In order to make a call dynamically insert a new <script> tag into your page. The source of that script tag attribute is set to a resource in another domain. This URL includes a callback parameter corresponding to a local JavaScript function. The server in the other domain responds with JavaScript that calls this function, passing JSON as an argument. The client then evaluates this JavaScript, giving it access to the server’s data.

Here is the javascript code that makes the JSONP request.

<html>

<head>

// function to make cross domain call

function loadScript(url)
{
// adding the script tag to the head
var head = document.getElementsByTagName(‘head’)[0];
var script = document.createElement(‘script’);
script.type = ‘text/javascript’;
script.src = url;

// fire the loading
head.appendChild(script);
}

function callbackfn(json){

//handle the json

}

</head>

<body>

<button id=”load” onclick=’loadScript(“url&callback=callbackfn”)’>Deals</button>

</body>

</html>

The following link is an app that is used to get deals around you using jsonp to make the call to an external API.

Jquery’s .ajax() method can be used to make cross domain requests but the app would be much lighter if we use JSONP since we dont have to include the jquery library.

JSONP is only useful if we have to make GET request to the external domain. We can’t use POST as a request method

Advertisements

HTML5 GeoLocation

Many websites can benefit from knowing exactly where the user accessing their site is from, enabling a more personalized local experience. As part of the HTML5 efforts, the W3C has developed a set of APIs to effectively allow the client-side device (i.e. your iPhone 3G+, Android 2.0+ phones, or even your conventinal desktop browsers) to retrieve geographic positioning information with JavaScript.

To get the current position, use the getCurrentPosition() API call. When called, it must immediately return and then asynchronously acquire a new Position object. If successful, this method must invoke its associated successCallback argument with a Position object as an argument. If the attempt fails, and the method was invoked with a non-null errorCallback argument, this method must invoke the errorCallback with a PositionError object as an argument.

In order to protect the privacy of the user, when the browser is loaded the user is initially prompted to disclose this current location of deny it.

This is the prompt on Firefox.

Here is the code snippet that is used to obtain the current position.

<!DOCTYPE html> // indicate that it is a HTML5 doc
<html>
<head>

<!– initialize for google maps –>
<meta name=”viewport” content=”initial-scale=1.0, user-scalable=no” />

</head>

<body onload=”initialize()”>

</body>

</html>

function initialize() {
if (navigator.geolocation)
{
navigator.geolocation.getCurrentPosition(handle_geolocation_query, handle_errors);
}

function handle_errors(error)
{
switch(error.code)
{
case error.PERMISSION_DENIED: alert(“user did not share geolocation data”);
break;

case error.POSITION_UNAVAILABLE: alert(“could not detect current position”);
break;

case error.TIMEOUT: alert(“retrieving position timedout”);
break;

default: alert(“unknown error”);
break;
}
}

function handle_geolocation_query(position){
clat = position.coords.latitude;
clng = position.coords.longitude;

console.log(‘values to map current location’ + ‘lat: ‘ + clat + ‘ lng: ‘ + clng);

}
}

Many kinds of applications and games can enriched by adding automatic location information. The location API can be paired up with google maps, bing maps or proprietary geolocation data to provide compelling solutions.

In this post I will show how to pair location API with google maps.

To display the position on the map we need to include the google maps library in the head tag.

<script type=”text/javascript” src=”http://maps.google.com/maps/api/js?sensor=false”></script&gt;

sensor=false implies that the devise has no inbuilt location detection capabilities, like GPS.

The location API response contains, the coords and timestamp fields. The timestamp field simply denotes the time at which the instance of geolocation data was created. The coords attribute contains a set of geographic coordinates together with their associated accuracy, as well as a set of other optional attributes such as altitude and speed.

Before initializing the map we need to create a LatLng object with the latitude and longitude.

Initializing the Map

var myLatlng = new google.maps.LatLng(38,-97);
var myOptions = {
zoom: 3,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP
}
mymap = new google.maps.Map(document.getElementById(“map”), myOptions);

map” is the id of the div in the body of the html.

Once we have initialized the map, we can add markers to the map and display information for each marker. Store the initialized map and latitude and longitude in global variables called mymap, clat, clng so that they can be used through out the code.

// function for adding a marker to the page.
function addMarker(location, message) {
marker = new google.maps.Marker({
position: location,
map: mymap,
animation: google.maps.Animation.DROP
});

addInfoWindow(marker, message)
}

// function to add info window for markers
function addInfoWindow(marker, message) {
var cinfoWindow = new google.maps.InfoWindow();
var chtml = message;

google.maps.event.addListener(marker, ‘click’, function() {
cinfoWindow.setContent(chtml);
cinfoWindow.open(mymap, marker);
});
}

// function to drop marker at currentlocation
function CurrentLocation() {
Marker1=new google.maps.LatLng(clat, clng); addMarker(Marker1, “Current Location”);
}

The complete code for this app is available at the following github repository.