Monday, March 9, 2015

Cross Domain API request using AJAX and JQuery

We often get into a requirement to read or post a data to an third party cross domain server through their exposed API’s.  We have plenty of straightforward options if we do it from the server side coding, but in the case of doing it from a client call we may get into “cross domain not allowed” error thrown by all browsers.

Here, will show you the one of the cross domain call approach using “JSONP”.

In this example I’m making GET request to Bright cove api  and getting response as JSONP:

NOTE: Using JSONP only we can do GET requests. POST requests is not possible.

<html>
<head>
<script src="http://code.jquery.com/jquery-latest.js"></script>
</head>
<body>
<script>
(function() {
  var mediaAPI = "http://api.brightcove.com/services/library?callback=?";
  $.getJSON( mediaAPI, {
    command: "search_videos",
    video_fields: "videoStillURL,thumbnailURL,id,name",
    media_delivery: "http",
    token: "ZY4Ls9Hq6LCBgleGDTaFRDL..............",
    format: "jsonp"
  })
  .done(function( data,status ) {
alert(status);
 $.each(data, function(i, field){
        alert(data.items[0].name);
                
            });

  });
})();</script>
</body>
</html>

})();</script>
</body></html>

No comments:

Post a Comment