(SOLVED) Wikipedia viewer - Codepen refreshing on button click?

I just started setting up my Wikipedia viewer project but I’m seeing some weird behavior and I cannot figure out why it is happening. If I enter a term and press enter or click the submit button, it looks like the entire page refreshes? I can see content load in my targeted div but then it quickly disappears.

Can someone please explain why this happens?

You have to delete form tag from yout html. You close after the button and this create an issue. :slight_smile:

1 Like

That did the trick. But why does the form tag cause issues? And is it not necessary to wrap my input and button in a form tag?

You do not have to use the form tag unless you are actually going to be submitting data to another page directly. By using getJSON, this is performed behind the scenes without directly posting to another page. If you wanted to keep the form tags, you will need to disable the default action of loading a new page when a form is submitted. Since your form does not have an action attribute which would indicate what page to load on submit, it just reloads the current page. Why causes the page to submit? When a form has a button, when it is clicked (regardless if it has type=“submit”), it will cause the form to submit. How can you use form tags and not have the form submit? You can take advantage of the event object which can be accessed by the first argument of the click callback function and then use the preventDefault method of the event object like:

  myClickEvent.preventDefault();  // this prevents the form from submitting on the button click
  var searchTerm = $('#searchTerm').val();
  $.getJSON("https://en.wikipedia.org/w/api.php?action=opensearch&search=" + searchTerm + "&limit=5&namespace=0&format=json&origin=*", function(a){

Thank you so much for that explanation!