Reputation: 119
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
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.
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