2

$('#searchButton').click(function(){
  var searchInput = "";
  searchInput = document.getElementById('test');
  if(searchInput.value !== ""){
    $.getJSON('https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch='+searchInput+'&utf8=', function(json){
      alert(json.query.search[0].title);
    });
  }
});

I'm confused on why the Json doesnt seem to be loading into the page. It seems like the whole operation stops at the url as even if i enter a string into the alert it doesn't run either...

Aruna
  • 11,959
  • 3
  • 28
  • 42
  • probably it's CORS. Did you see any messages on console? – Alexan Dec 25 '16 at 00:50
  • https://stackoverflow.com/questions/37106041/does-wikipedia-api-support-cors-or-only-jsonp-available – Alexan Dec 25 '16 at 00:51
  • This is the message i got on the console `index.html:1 XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&list=search&format=json&srsearch=[object%20HTMLInputElement]&utf8=. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.` Im not quite sure what all this means but thanks for the help im sure ill get it figured out. – Graham Gillmore Dec 25 '16 at 00:57
  • use JSONP instead – Alexan Dec 25 '16 at 00:58

1 Answers1

1

You got this error because CORS is not enabled for the origin from which you are calling the mediawiki and you can check the same more about here.

https://www.mediawiki.org/wiki/Manual:CORS

You can use jQuery jsonp request as below with dataType: 'jsonp' instead.

Working snippet:

$(document).ready(function() {

$('#searchButton').click(function(){
  var searchInput = "";
  searchInput = document.getElementById('test');
  if(searchInput.value !== ""){
    
    $.ajax( {
    url: 'https://en.wikipedia.org/w/api.php',
    data: {
        action: 'query',
        list: 'search',
        format: 'json',
        srsearch: searchInput.value
    },
    dataType: 'jsonp'
} ).done( function ( json ) {
    alert(json.query.search[0].title);
} );
    
  }
});
  
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="test" />
<input type="button" id="searchButton" value="Search" />
Aruna
  • 11,959
  • 3
  • 28
  • 42