javascriptjquery-uiwikimedia

how to use a jquery ui autocomplete function with wikimedia opensearch api?


https://en.wikipedia.org/w/api.php?action=opensearch&search=a&limit=10&namespace=0&format=json

the above webpage returns a json array with nested arrays. I just want the second nested array with the titles. How can i use it with jquery ui autocomplete function so that i can use it only with the array of titles.


Solution

  • Here is a basic example. This is based on Autocomplete | Remote JSONP Datasource example.

    Working Example: https://jsfiddle.net/Twisty/t3ahcdht/

    HTML

    <label for="wiki">Wiki:</label>
    <input id="wiki">
    <button>Go</button>
    

    JavaScript

    $(function() {
      $("#wiki").autocomplete({
        minLength: 1,
        source: function(req, resp) {
          $.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + req.term + "&limit=10&namespace=0&format=json&callback=?", function(json) {
            console.log(json);
            resp(json[1]);
          })
        }
      });
    });
    

    This helps address the issue with CORS. From https://en.wikipedia.org/wiki/Same-origin_policy,

    In computing, the same-origin policy is an important concept in the web application security model. Under the policy, a web browser permits scripts contained in a first web page to access data in a second web page, but only if both web pages have the same origin. An origin is defined as a combination of URI scheme, hostname, and port number. This policy prevents a malicious script on one page from obtaining access to sensitive data on another web page through that page's Document Object Model.

    And...

    Cross-Origin Resource Sharing

    The second technique for relaxing the same-origin policy is standardized under the name Cross-Origin Resource Sharing. This standard extends HTTP with a new Origin request header and a new Access-Control-Allow-Origin response header. It allows servers to use a header to explicitly list origins that may request a file or to use a wildcard and allow a file to be requested by any site. Browsers such as Firefox 3.5, Safari 4 and Internet Explorer 10 use this header to allow the cross-origin HTTP requests with XMLHttpRequest that would otherwise have been forbidden by the same-origin policy.

    This will allow us to GET results from the API with the search term entered by the user and display the results in the autocomplete. Response speed will vary.