2

How can i get data (json format) from another domain?
My problem is: I want to get data from: http://pin-codes.in/api/pincode/400001/
I have tried to use CORS but it didn't work.
My console is:
GET http://pin-codes.in/api/pincode/400001 [HTTP/1.1 200 OK 780ms]
Error Error
My code by client-script:

$(document).ready(function() {
 $("#get_data_btn").click(function() {
   var data_path = "http://pin-codes.in/api/pincode/400001";
   $.getJSON(data_path, null)
    .done(function(data) {
      console.log("Success: " + data.status);
    })
    .fail(function(jqxhr, textStatus, error) {
      console.log("Error Error");
    });
 });
});
user3089480
  • 101
  • 1
  • 11
  • possible duplicate of [Ways to circumvent the same-origin policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – Felix Kling Dec 11 '13 at 04:30

3 Answers3

3

You probably don't own the other domain right?

No problem at all. Never mind nay-sayers, in computing everything is a yay!

Just use a simple proxy on your server or look into YQL.

this simple query will work:

select * from json where url="http://pin-codes.in/api/pincode/400001/ "

Just test this link (bypassing cross-domain security bull$#!7).
It will get the data you requested as normal plain json (no jsonp) data wrapped in callback-function cbfunc.

Have a look at this question for further info (I did quite a lot of yql scrape answers on SO).


Update:

Here is a crude fiddle demonstrating the whole process: so you enter a url, click fetch and watch the magic happen: http://jsfiddle.net/NbLYE/

function getJSON(url) {  //quick and dirty
  var script = document.createElement('script');
  script.setAttribute('src', url);
  script.setAttribute('type', 'text/javascript');
  document.getElementsByTagName('head')[0].appendChild(script);
}

function cbfunc(json){     //the callback function
   if(json.query.count){ 
      var data=json.query.results.json;
      // do your work here, like for example:
      //document.getElementById('output').innerHTML=data.toSource();
   } else {
      alert('Error: nothing found'); return false;
   }
}

function fetch(url){         //scrape the url you'd want
   var yql="select * " + 
           " from json" +
           " where url='" + url + "';";
   yql="http://query.yahooapis.com/v1/public/yql?q=" +
       encodeURIComponent(yql) +
       "&format=json" +
       "&callback=cbfunc";
   getJSON(yql);
}

That should get you started (and motivated that it is easy).

Hope this helps!

Community
  • 1
  • 1
GitaarLAB
  • 14,536
  • 11
  • 60
  • 80
  • Everything is ok on http://jsfiddle.net/NbLYE/. But when i run your code on Firefox, Chrome that I have a problem: RefernceError: cbfunc is not defined. What does it mean? – user3089480 Dec 11 '13 at 09:09
  • Just to check I understand correctly: if you run the fiddle in those browsers (FF and Chrome), then everything works without error (as I expect it), but inside your own code it doesn't? If so: Do you have a (globally available) function named (or referenced as) `cbfunc` and is this function error-free? Is the cbfunc function defined BEFORE you actually 'fetch' the url (order of operation)? Otherwise, try to setup a fiddle, I'll look at it. – GitaarLAB Dec 11 '13 at 10:20
1

You don't have the correct CORS headers on your server.

You need to add

Access-Control-Allow-Origin: *

(or something similar) server-side to the response.

Edit: From the HTTP response, it appears you are using PHP. Use the header function in your response.

<?php header('Access-Control-Allow-Origin: *'); ?>
Paul Draper
  • 78,542
  • 46
  • 206
  • 285
  • See updated answer. If that is not clear, include your server-side code in your question, since that is where the problem is. – Paul Draper Dec 11 '13 at 04:17
  • The server: http://pin-codes.in/api/pincode/400001/ is not mine. So, I can not access it to add CORS headers. I just code in html file and open it. – user3089480 Dec 11 '13 at 04:21
  • What PHP? All I see is JavaScript code. And I don't believe OP has control of the pin-codes.in server. – Michael Geary Dec 11 '13 at 04:21
  • In that case, you cannot do this from the browser. The "owner" of that server has not chosen to allow you to request that data from another webpage. – Paul Draper Dec 11 '13 at 04:22
  • And @MichaelGeary, the PHP came from the `X-Powered-By` header. – Paul Draper Dec 11 '13 at 04:23
  • I think this: when we enter the link (http://pin-codes.in/api/pincode/400001/) on browser, it responses json data. We can see it. So, maybe have a way to parse this responsed data without the "owner" permission. – user3089480 Dec 11 '13 at 04:28
  • That `X-Powered-By` header isn't coming from OP's server, it's the server he or she is trying to access. It wouldn't make any difference for OP's purposes if they were using PHP or Ruby or Python or whatever. – Michael Geary Dec 11 '13 at 04:29
  • @user3089480 - You can look at the data directly in a browser when you enter the URL, but that doesn't mean you'll be able to do it in JavaScript. The browser security won't let you. If the server in question doesn't support JSONP or CORS, then you have to use a server language yourself, like the PHP code suggested in the other answer. – Michael Geary Dec 11 '13 at 04:31
  • @GitaarLAB, that is *totally wrong*! Imagine if someone could access all of your Facebook/Google+/Twitter data when you are on their website. (Remember, cookies for that domain are sent with your browsers request to the domain!) – Paul Draper Dec 11 '13 at 04:35
  • @GitaarLAB, right. And distinguishing which data is private and which is public is the *entire reason* for CORS headers. – Paul Draper Dec 11 '13 at 04:43
1

You can't do it using jquery only, you can use any server side script like PHP

Try using php,

<?php
    echo file_get_contents('http://pin-codes.in/api/pincode/400001');
?>

Save above code in pincode.php and use jquery like,

$(document).ready(function() {
    $("#get_data_btn").click(function() {
        var data_path = "pincode.php";
        $.getJSON(data_path, null)
            .done(function(data) {
                console.log("Success: " + data.status);
            })
            .fail(function(jqxhr, textStatus, error) {
                console.log("Error Error");
            });
    });
});

Also read this

Community
  • 1
  • 1
Rohan Kumar
  • 40,431
  • 11
  • 76
  • 106
  • I think this: when we enter the link (pin-codes.in/api/pincode/400001) on browser, it responses json data. We can see it. So, maybe have a way to parse this responsed data without the "owner" permission. Is it right? – user3089480 Dec 11 '13 at 04:31
  • You misunderstood my mind. I mean that maybe there is a way to parse the json data without use server side script? Because we can see the responsed json data when wen enter the link: http://pin-codes.in/api/pincode/400001/ – user3089480 Dec 11 '13 at 04:42
  • These url's may help you http://stackoverflow.com/questions/3481977/is-there-a-way-to-bypass-javascript-jquerys-same-origin-policy-for-local-acce and http://stackoverflow.com/questions/11299438/jquery-how-to-remove-cross-domain-limitation – Rohan Kumar Dec 11 '13 at 05:10