How to call external site url using jQuery / AJAX

Recently I worked on a project where I had to pull data from an external site and populate a select on client’s website. Initially I thought it would be quite easy and straight forward. I used jQuery ajax request to fetch the data. But to my surprise I was not getting request call or any response. After struggling for atleast an hour I remembered Same origin policy

Then I figured out you can call the external url provided it gives the response in JSONP format. Below code worked for me.

$.ajax({
url: externalURL,
dataType: ‘jsonp’,
success: function(data){
// write your code here
}
});

If external site does not give JSONP response, you can call the url using iframe and then assign the response to field that you want. I have not tried this approach but it should work.

Hope this helps…

3 thoughts on “How to call external site url using jQuery / AJAX”
  1. You sir, are a lifesaver. I searched for something like this for days. I can’t thank you enough!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.