Adam
Adam

Reputation: 119

How to use Wikipedia API to search for values input by a user?

I am new to programming and web development so I don't know how to use the correct Ajax/JSON. I am using HTML and jQuery. I have created text input field with a submit button underneath, I want my page to search for the value in this input field and return results.

I found this jQuery code to do it, but I do not understand the format of the url.

$("#search").click(function(){

    var searchTerm = $("#searchTerm").val();// value entered by the user
    var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search="+ searchTerm + "&format=json&callback=?"; // url to look for using the search input by the user

    $.ajax({
        type:"GET",
        url:url,
        async:true,
        dataType: "json",
        success:function(data){
            console.log(data[1][0]);
            console.log(data[2][0]);
            console.log(data[3][0]);
        },

        error: function(errorMessage){alert("Error");}
    });
});

the input field is like this:

<input class="form-control" id="searchTerm">
<button id="search" type="button" class="btn btn-primary">Submit</button>

Upvotes: 2

Views: 3253

Answers (1)

Chintan
Chintan

Reputation: 773

There are a few things to know about the Wikipedia API.

Consider the url that you have shared:

var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search="+ searchTerm + "&format=json&callback=?";

There are two parts in the API URL.

  1. The API Entry Point: https://en.wikipedia.org/w/api.php - This is the URL to which you make all your API calls i.e. it is the part common to all API calls.
  2. Parameters: The rest of the URL are parameters. In the parameters, you specify what exactly you want from the API call. I am explaining some of the parameters below:

action parameter: There are many action parameters available in the Wikipedia API. action=query parameter is used to get information about a wikipedia article. Another common action parameter is action=opensearch which is used to search Wikipedia - which is also there in the URL above. To read more on the Action parameter go here.

Each action parameter also may have its own sub-parameters. For example, the search parameter which is used in the url above. It tells the API what term to search for.

format parameter tells which format you want the result in. It is usually json though php and xml are also supported but deprecated. More on this here.

callback=? may have been added in your query to trigger a JSONP response to avoid violation of Same Origin Policy. More information on Cross Site Requests regarding the Wikipedia API are available here.

`

Upvotes: 5

Related Questions