Search code examples
codepen

JQuery Ajax prepended data disappears


So I'm building a wikipedia viewer and trying to import data from wikipedia and prepend it to an unordered list (#output).

The problem arises when I type something in the input field and hit the #search button. For a split second the content is listed then it disappears, like I'm refreshing the page.

Here is the code:

$(document).ready(function() {

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

    var searchTerm = $("#searchTerm").val();
    var url = "https://en.wikipedia.org/w/api.php?action=opensearch&search="+ searchTerm +"&limit=5&callback=?"

    $.ajax({      
      type: "GET",
      url: url,
      async: false,
      dataType: "json",
      success: function(data) {

        for (var i = 0; i < data[1].length; i++) {        
        $("#output").prepend("<li><a href = "+ data[3][i] +">"+ data[1][i] +"</a><p>"+ data[2][i] +"</p></li>");
        };

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


    });
  });

});

I'm doing this in Codepen for a freeCodeCamp project. Here is the link to the pen I wrote in, so that you can see for yourself what the problem is:

Wikipedia Viewer

This is my first post, hope I'm doing it right. Tried to search for the solution but couldn't solve it. Thanks in advance!


Solution

  • You form is being submitted when you press the submit button.

    You can capture the onSubmit event of the form and return false to prevent it from being submitted. You can add an id to your form to be able to select it easily with jQuery.

           $("#myForm").submit(function(e){
              return false;
            });
    
           <form id="myForm" class = "pure-form pure-form-aligned">
             <button class = "button-error pure-button" id = "search">Submit</button>
             <input class = "pure-input-2-3" id = "searchTerm">
             <ul id = "output"></ul>
           </form>
    

    CodePen