How to request data from a
server in a different domain?
In
my previous post I had shown you “How to create watermark for pdf using php script ?”. Today
I am going to write about jquery cross site ajax call to retrieve data from
different domain. We can solve this using ‘JSONP’.
Let us know first “ What
is JSONP ? “
JSONP
JSONP is JSON with padding.
JSONP is a technique that
allows you to transfer JSON data across multiple
domains. For security reasons browser does not allow script from remote domain
to run. We are going to use JSONP to solve this. Cross domain ajax refers
to the idea of making requests across domains in opposition to the same origin
restriction. Padding or prefix is
typically name of callback function. The response to the JSONP is not json and
not parsed as json also, It is javascript expression which invokes a function
call on some json formatted data.
How is it
works ?
It’s makes sense when used with script tag. For each new
JSONP request browser add a new <script> tag or use existing one. The url
request pointed to by the <script>’s src attribute returns JSON data,
with a function call wrapped around it.
You can follow below script to do ajax request to cross
site. For client side jquery –
$.ajax({
dataType: ‘jsonp’,
url : ‘http://www.example.com/getuserdetails’,
data: ‘userid=204’,
jsonp: ‘js_callback’,
success: function() {
// Do your stuffs on
alert(“Successfully requested
cross domain with jquery ajax ”);
}
});
Php script given below :
function getuserdetails()
{
$data = array();
$data = getuserDataBYID($_GET[‘userid’]);
echo $_GET[‘js_callback’].”(”.json_encode($data).”);”;
}
Jsonp is
fastest and easiest way to get json data from remote servers with javascript.
It allowing including script tags from remote servers allows the remote servers
to inject any content into a website. So if the remote servers hae
vulnerabilities that allow javascript injection. So in that way it’s increased
the risk also.
Hope this post will help you all to know about cross domain ajax
request using JSONP callback. Keep visiting for new interesting posts here and
please join my groups in linkedin, facebook to keep up to date. Please share
your ideas here and do post if you have any new things to share with everyone. If
you like my post please leave a comment here. All the best. Have a good day
ahead.
You also can join my group for latest technology updates in
below link,
To join in LinkedIn :
http://www.linkedin.com/groups?about=&gid=4300612
To join in LinkedIn :
http://www.linkedin.com/groups?about=&gid=4300612
To Join in Facebook:
http://www.facebook.com/pages/Open-source-Web-Developers-Programmers/275124762559654?sk=wall
http://www.facebook.com/pages/Open-source-Web-Developers-Programmers/275124762559654?sk=wall
To Join in Google+ :