Andy Andy - 3 months ago 18
Ajax Question

Wiki API request not working

I used some sample code from the Wiki API docs but when I enter a search item, nothing happens. No errors in the console, just nothing. The URL itself works if I enter it into a browser so I think something with the code is not passing in the proper value. Is there an issue with how I'm calling the API? Below is the relevant code:

$(document).ready(function(){
$('#search-submit').click(function() {
getWiki($('#searchVal').val());
});
/*add code for get lucky function*/
});

function getWiki(searchParam) {
$.ajax( {
url: 'http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page='+searchParam+'&callback=?',
dataType: 'json',
type: 'POST',
headers: { 'Api-User-Agent': 'Example/1.0' },
success: function(data) {
var result = data;
pageTitle = result.title;
$(".search-box").html(pageTitle);
}
});
};


Here is the HTML:

<body>
<div class="container">
<div class="col-lg-12 header">
<h1>Search Wiki</h1>
</div>
<div class="row search-box">
<div class="col-lg-10">
<input placeholder=" Search" class="input" type="text" id="searchVal" name="searchVal"/></div>
<div class="col-lg-2"><button type="submit" id="search-submit" name="search-submit" class="btn-default">
<i class="fa fa-search fa-2x"></i>
</button></div>
</div>
<div class="row button-box text-center">
<div class="col-lg-12">
<button type="button" class="btn btn-primary" id="random">I'm Feeling Lucky</button></div>
</div>
</div>
</body>

Answer

The returned JSON has a parse property before the result, so it has to be data.parse.title to get the title etc.

$(document).ready(function() {
    $('#search-submit').click(function() {
        getWiki($('#searchVal').val());
    });
    /*add code for get lucky function*/
});

function getWiki(searchParam) {
    $.ajax({
        url: 'http://en.wikipedia.org/w/api.php?action=parse&format=json&prop=text&section=0&page=' + searchParam + '&callback=?',
        dataType: 'json',
        type: 'POST',
        headers: {
            'Api-User-Agent': 'Example/1.0'
        },
        success: function(data) {
            var result = data.parse;
            var pageTitle = result.title;
            $(".search-box").html('The title is : ' + pageTitle);
        }
    });
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Search for something : <input id="searchVal"><button id="search-submit">Search</button>
<br /><br /><br />
<div class="search-box"></div>