Thursday, September 12, 2013

Simple Cross-Domain Service Call via JSONP using JQuery

Objective:

Retrieve data from a different domain and dynamically display them in your web page.

Introduction:

What if you want to make your web page display data dynamically? You can use AJAX to achieve this. All you have to do is fire up your AJAX, request data from the service which you created, and do some javascript stuff to update your DOM. As simple as that.
Now, what if you were in a situation where your supposedly dynamic web page resides in a different domain from where your data is coming from. Initially you will think AJAX to the rescue, again. That would be nice but it doesn’t work that way.
There is a thing called Same-Origin policy which prevents AJAX from calling a service from a different domain. Sucks doesn’t it? I know I’ve been there. And this is why I want to share a solution and explain it as simple as I can. Please read on.

Procedure:

Server Side

create a php script named server.php. with the following content

<?php
header("Access-Control-Allow-Origin: *");
header('content-type: application/json; charset=utf-8');
$data = [
    ['name' => 'uma'],
    ['name' => 'tykia'],
    ['name' => 'miranda'],
    ['name' => 'de guzman']
];
echo json_encode($data);
?>



Client side:

Create a file named client.html with the following content:

<!doctype html>
<html>
    <head>
        <script type="text/javascript" src="//code.jquery.com/jquery-1.11.2.min.js"></script>
    </head>
    <body>
        test
        <script>
            $(function () {
                var url = "http://www.servercom/server.php";
                $.ajax({
                  dataType: "json",
                  url: url,
                  data: {},
                  success: function(r){
                      alert(JSON.stringify(r));
                  },
                  error: function(a,b,c){
                      alert(a);
                      alert(b);
                      alert(c);
                  }
                });
            })
        </script>
    </body>
</html>

Replace the url with the actual url of the server-side script

I hope it helps

No comments:

Post a Comment