Why does my code require a search twice before i get the final result?(Wiki Search)

So this is what it does lets say i search apples.The first search i may get a blink of the data being pulled. Then the second search of apple i get the information required fully.

This is the codepen if you want to see the bug: https://codepen.io/chrism3ca/full/ryPJzW/

     $( document ).ready(function() {
          
           //Getting the input value when keydown is enter
           $("#searchBar").on("keydown",function search(e) {
             var newSearch;
            if(e.keyCode == 13) { 
                
               newSearch = $('#searchBar').val();
            //Requesting data from api
                 $.ajax({ 
            type: 'GET',
            url:"https://en.wikipedia.org/w/api.php?action=opensearch&search="+newSearch+"&limit=10&namespace=0&format=json", 
            data: {
                format: 'json' 
            },
            dataType: 'jsonp',
            success: function(data){
             
             //printing similar titles
             for (i=0; i < data[1].length; i++){
                
                       $('#searchTitle').append(data[1][i] + "</br>");
             
               }
              //printing summary
              for (k=0; k < data[2].length; k++){
                
                       $('#Summary').append(data[2][k] + "</br>");
             
               }
            }
          });
              
              }    
        });   
        });

I cleaned up your code.
You need to use triple backticks to post code to the forum.
See this post for details.

I’m not seeing this bug. Have you fixed it already? Which browser are you using?

1 Like

Whenever I have problems, I like to simplify. Simplifying your code a bit, I get:

$( document ).ready(function() {
  var newSearch = 'apple';
  $.ajax({ 
    type: 'GET',
    url:"https://en.wikipedia.org/w/api.php?action=opensearch&search="+newSearch+"&limit=10&namespace=0&format=json", 
    data: {
      format: 'json' 
    },
    dataType: 'jsonp',
    success: function(data){
      //printing similar titles
      for (i=0; i < data[1].length; i++){
        $('#searchTitle').append(data[1][i] + "</br>");
      }
      //printing summary
      for (k=0; k < data[2].length; k++){  
        $('#Summary').append(data[2][k] + "</br>");
      }
    } //success function
  }); //ajax
});   

with the following HTML:

<h1>Search Titles</h1>
<div id = 'searchTitle'></div>
<h1>Summaries</h1>
<div id = 'Summary'></div>

And it works quite nicely.

Does that help? If not, please include all of the code or a link to the pen.

1 Like

Thanks for the help guys i fixed the error i was submitting the input twice once with the form tag and once with the keypress event. Also @ksjazzguitar thanks for the tips.