0

I'm completely new to JavaScript/jQuery, so as a nice "HelloWorld" project I wanted to build a webpage which simply grabs a random Wikipedia article and shows the header and first paragraph. Googling around, it looks like ajax is the way to do this, so I wrote the simple script (with a fixed url for now):

<script>
    $(document).ready(function () {
        $.ajax({
            url: 'https://en.wikipedia.org/wiki/Flemingdon_Park',
            type: 'GET',
            dataType: "html",
            success: function (data)
            {
                alert('Success!');
                $('#MainHeader').html($(data).find('#firstHeader').html());
            },
            error: function (xmlHttpRequest, textStatus, errorThrown)
            {
                var serverNotReached = xmlHttpRequest.readyState == 0 || xmlHttpRequest.status == 0;
                if (serverNotReached)
                    alert("No response from the server!");
                else
                    alert(errorThrown);
            }
        });
    })
</script>

My problem is that I only ever get the "No response from the server" from wikipedia. I tried doing a GET with Postman and the exact same url, and that returned the html as I expected. Next I tried the script with http://stackoverflow.com, but same thing. Finally, I tried http://www.msn.com and that did work. I'm assuming there is something fundamental I am missing here, but I'm not sure what.

Dumpster Fire
  • 111
  • 1
  • 2
  • 7
  • 3
    I got "No 'Access-Control-Allow-Origin' header is present on the requested resource." See [this post](http://stackoverflow.com/questions/20035101/no-access-control-allow-origin-header-is-present-on-the-requested-resource) for more information. – showdev Sep 04 '15 at 16:39
  • 1
    Also => chrome packaged apps (like Postman) can have cross domain permissions, that's why it's working there – cviejo Sep 04 '15 at 16:41
  • 3
    https://en.wikipedia.org/w/api.php is what you are really looking for. – Kijewski Sep 04 '15 at 16:43
  • @showdev - That sounds like the answer, thanks you! Out of curiousity, why did the msn url not have the same issue? – Dumpster Fire Sep 04 '15 at 16:51
  • msn.com seems to be configured with `Access-Control-Allow-Origin: *` – showdev Sep 04 '15 at 16:59

2 Answers2

0

Sounds like you're violating Cross Origin Resource Sharing

Try JSONP? If you're just messing around and don't have security concerns.

Jacob Petersen
  • 1,463
  • 1
  • 9
  • 17
0

http://en.wikipedia.org/w/api.php is what you are looking for. It has a very elaborated documentation and supports JSONP:

Change format=jsonfm to format=json.

Kijewski
  • 25,517
  • 12
  • 101
  • 143