Search code examples
jqueryjsonapiwikimedia

Retrieving JSON data from Wikipedia API using jQuery


I have tried every combination I could find on here and the Wikimedia API site, still I can't seem to get any data returned. This is my code,

$('#go').click(function () {
    var str = $("#input").val();
    var fullstr = 'https://en.wikipedia.org/w/api.php?format=json&action=query&list=search&srnamespace=0&srsearch=' + str + '&srprop=snippet&format=json&callback=json';
    $.getJSON(fullstr, function(data) {
      alert(data);
    });
  });

I have tested it up until the getJSON call and it seems to be working, but I don't seem to be getting anything from the call. (The final alert() is just to check for any object being returned).

What is the problem?

Thanks!


Solution

  • It could be helpful to you, while framing a URL you need to pass origin= *

    $(document).ready(function(){              
         $("#searchWiki").click(function(){
              var q = document.getElementById("searchid").value;
              $.getJSON("https://en.wikipedia.org/w/api.php?action=query&format=json&gsrlimit=15&generator=search&origin=*&gsrsearch=" + q, function(data){
         console.log(data)
         });
       });
     });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
        <div id="search">                    
             <input id="searchid" class="input-lg" name="gsrsearch" type="text" placeholder="search Wiki" autocomplete="off"/>
             <button id="searchWiki" class="btn-lg btn-info">Search</button>                          
        </div>