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:
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 XMLHTTPRequest
object 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
Tweet
1 comment:
that JSFiddle doesn't work.
Post a Comment