jQuery: IP address using JSONP

In this post, we will see how to find the IP address of the client machine using a service which is JSONP compatible.

What is JSONP?

When you are using Ajax, you cannot do cross-domain calls. In simple words, you cannot make Ajax requests from a different domain/server other than your server. A common approach adopted earlier as a workaround was to use a proxy Web Service and then access the data kept on a different server, but this approach was slower as it required two or more calls to fetch the data.

JSONP or "JSON with padding" is a method used to bypass the cross-domain policies in web browsers. Using JSONP, you can dynamically insert JavaScript with JSON Data, from different domains. You just need to make sure that the third party Service supports JSONP.

JSONP is a very simple way to get JSON data from ‘other domains’. For those new to JSONP, Read more here

Retrieve IP address using JSONP

Let us see how to retrieve your IP Address using JSONP and jQuery. Use the following code:

jQuery JSONP IPaddress

In the code above, we are calling a service which supports JSON calls. If the request URL includes the string "callback=?", the request is treated as JSONP.

Note: As of jQuery 1.5, all of jQuery's Ajax methods return a superset of the XMLHTTPRequestobject i.e. the jQuery XHR object. Read more here

JSONP comes with its own set of security risks. Read this article to see one of the ways to minimize the risks.

See a Live Demo

Will you give this article a +1 ? Thanks in advance

About The Author

Suprotim Agarwal
Suprotim Agarwal, ASP.NET Architecture MVP (Microsoft Most Valuable Professional) works as an Architect Consultant and provides consultancy on how to design and develop Web applications.

Suprotim is also the founder and primary contributor to DevCurry, DotNetCurry and SQLServerCurry. He is the Editor of a Developer Magazine called DNC Magazine. He has also written two EBooks 51 Recipes using jQuery with ASP.NET Controls. and The Absolutely Awesome jQuery CookBook

Follow him on twitter @suprotimagarwal

1 comment:

Anonymous said...

that JSFiddle doesn't work.