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...

4
  • probably it's CORS. Did you see any messages on console? Commented Dec 25, 2016 at 0:50
  • stackoverflow.com/questions/37106041/… Commented Dec 25, 2016 at 0: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. Commented Dec 25, 2016 at 0:57
  • use JSONP instead Commented Dec 25, 2016 at 0:58

1 Answer 1

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" />

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.