0
$(document).ready(function(){

    $(".btn").click(function(){
        var x=$("#srh").val();
        var ur="https://en.wikipedia.org/w/api.php?action=query&titles="+x+"&prop=info&format=json";
        $.getJSON(ur, function(json) {
            $(".test").html(JSON.stringify(json));
         });
    });

});

I have made a search bar and when I enter a query and press the search button I want to print the json data I get from the Wiki API to my test div.Unfortunately when I press the button nothing happens.Any ideas?

stop
  • 7
  • 4
  • 1
    you're doing a cross-domain request, which won't work... check your browser's debug console. – Marc B Aug 23 '16 at 14:58
  • Related http://stackoverflow.com/questions/38703419/cannot-carry-out-ajax-request-from-wikipedia – yuriy636 Aug 23 '16 at 15:00
  • @MarcB I checked the console already.No errors. – stop Aug 23 '16 at 15:00
  • @stop You're not looking in the right place then: `XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&titles=asdf&prop=info&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'https://fiddle.jshell.net' is therefore not allowed access.` https://jsfiddle.net/woft8vzL/ – Jason P Aug 23 '16 at 15:03
  • @JasonP mhm,that's odd.Anyways,how can I fix this though? – stop Aug 23 '16 at 15:06
  • See if the api supports jsonp, or make the call from the server instead of directly from the browser. – Jason P Aug 23 '16 at 15:09
  • @stop Its not odd, I think you can use `JSONP` to query the wikipedia api from another domain. – Timigen Aug 23 '16 at 15:10

1 Answers1

0

You need to use and learn about JSONP. Following short code will work for you

   $.ajax({
      dataType: 'jsonp', url : ur,
      success:function(json){
          $(".test").html(json);            
      }});

A bit better explained version of above code. See this working

   $.ajax({
      dataType: 'jsonp', //!important
      url : ur,
      success:function(json){
        console.log(json); //to see response before stringifying it
        try{
          json = JSON.stringify(json);
          $(".test").html(json);
        }
        catch(e){
          console.log(e);
        }
      },
      error:function(a){
        console.log(a); //in case of request not processed
      }
    });
Community
  • 1
  • 1
Sami
  • 8,168
  • 9
  • 66
  • 99