Kyle Pryor
Kyle Pryor

Reputation: 27

.getJSON won't succeed even though URL works

HTML

<body>
    <header>
        <div class="container-fluid">
            <h1>Wikipedia Viewer</h1>
            <form id="userInput">
                <input id="query" type="text" name="userInput" value="" placeholder="Search">
                <input id="submitBtn" type="submit" name="send" value="Click!">
            </form>
            <a id="randomArticle" href="https://en.wikipedia.org/wiki/Special:Random"><i class="fa fa-random fa-2x" aria-hidden="true"></i></a>
        </div>
    </header>
    <div class="results">
         </div>
</body>

</html>

Javascript

 var url = "https://en.wikipedia.org/w/api.php?action=opensearch&datatype=json&callback=?&search=";
    var userQuery = "";
    var html = "";
    $(document).ready(function () {
        $("#userInput").submit(function (e) {
            userQuery = document.getElementById("query").value;
            $.getJSON(url + userQuery, function (data) {
                for (var i = 0; i < data[1].length; i++) {
                    html = '<article><a href="' + data[3][i] + '"target="_blank"><h3>' + data[1][i] + '</h3><p>' + data[2][i] + '</p></a></article>';
                    $(".results").append(html);
                }
            });
        });
    });

When I get to the .getJSON it just won’t succeed, I have tested the URL and the JSON comes up in browser but the request using Jquery just won’t work.

Upvotes: 2

Views: 69

Answers (2)

nyedidikeke
nyedidikeke

Reputation: 7618

All you need to do is to add a jQuery preventDefault() Method to your button click event as in:

$(document).ready(function () {
    $("#userInput").submit(function (e) {
        e.preventDefault();
        userQuery = document.getElementById("query").value;
        $.getJSON(url + userQuery, function (data) {
            for (var i = 0; i < data[1].length; i++) {
                html = '<article><a href="' + data[3][i] + '" target="_blank"><h3>' + data[1][i] + '</h3><p>' + data[2][i] + '</p></a></article>';
                $(".results").append(html);
            }
        });
    });
});

Upvotes: 2

Hassaan
Hassaan

Reputation: 3991

Can you log the success and fail method. Possibly, there can be Cross Origin issue, if that so then you need to add cors at server level.

You can log the success and failure as mentioned http://api.jquery.com/jquery.getjson/

// Assign handlers immediately after making the request,
// and remember the jqxhr object for this request
var jqxhr = $.getJSON( "example.json", function() {
  console.log( "success" );
})
  .done(function() {
    console.log( "second success" );
  })
  .fail(function() {
    console.log( "error" );
  })
  .always(function() {
    console.log( "complete" );
  });

// Perform other work here ...

// Set another completion function for the request above
jqxhr.complete(function() {
  console.log( "second complete" );
}); 

Upvotes: 0

Related Questions