0

I'm trying to submit something to search with the form and pull info from the j son

$("#target1").submit(function(e) {
  e.preventDefault();
  var x = document.getElementById("input").value;
  var url = "https://en.wikipedia.org/w/api.phpaction=query&format=json&prop=revisions&list=search&titles=&rvprop=content&srsearch=" + x;
  var the = function(teh) {
    $("#target2").text(teh.continue.continue);
  }
  $.getJSON(url, the);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="" id="target1">
  <input class='text-center' type='text' id='input' placeholder='Search 
    Wikipedia' required>
</form>
<div class='text-center'>
  <p id='target2'></p>
</div>

example link of json: https://en.wikipedia.org/w/api.php?action=query&format=jsonfm&prop=revisions&list=search&titles=&rvprop=content&srsearch=cats

I am trying to get the info from the titles but im just using the "continue" to make it shorter.
full code at http://codepen.io/nunez7890/pen/aWWXqy

nunez7890
  • 15
  • 3
  • Please mention the issue that you are facing. – Harshit Jain May 09 '17 at 06:34
  • The getJSON method is not calling the information I am asking for. – nunez7890 May 09 '17 at 06:40
  • You are getting a cross origin access error `XMLHttpRequest cannot load https://en.wikipedia.org/w/api.php?action=query&format=json&prop=revisions&list=search&titles=&rvprop=content&srsearch=hello%20world. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.` – Harshit Jain May 09 '17 at 06:47
  • Use ajax call with type as `JSONP`. `$.ajax({ url:url, dataType: 'jsonp', // Notice! JSONP <-- P (lowercase) success:the, error:function(){ alert("Error"); } });` Let me know if this works. – Harshit Jain May 09 '17 at 06:51
  • Looks like its CORS issue. Refer here for solution http://stackoverflow.com/questions/23952045/wikipedia-api-cross-origin-requests – rAjA May 09 '17 at 06:56
  • Yes, that worked. Now I'm trying to figure how to post that your comment was the answer. – nunez7890 May 09 '17 at 19:49
  • @nunez7890 I have added it as an answer. Please accept it so that other users may find it useful. – rAjA May 12 '17 at 04:30

1 Answers1

0

Looks like it's CORS issue. Refer here for solution Wikipedia API + Cross-origin requests

Add origin=* to the URL query params.

$("#target1").submit(function(e) {
  e.preventDefault();
  var x = document.getElementById("input").value;
  var url = "https://en.wikipedia.org/w/api.php?origin=*&action=query&format=json&prop=revisions&list=search&titles=&rvprop=content&srsearch=" + x;
  var the = function(teh) {
    $("#target2").text(teh.continue.continue);
  }
  $.getJSON(url, the);
});
Community
  • 1
  • 1
rAjA
  • 899
  • 8
  • 13