getJSON if statement issue

Hello!

I am working on the wikipedia app. My getJSON works fine outside of the if statement, but once I place it in there it not longer works. No errors that I can find in console either.

$('.submit_on_enter').keyup(function(event) {  
    if (event.keyCode == 13) {
      console.log($(this).val());
      url = "https://en.wikipedia.org/w/api.php?action=opensearch&search=hello%20world&limit=6&format=json&callback=?";
      
      $.getJSON(url, function(result){
            addPosts(result);
        });
      //addPosts($(this).val());
     
    }
});

//loop to add divs of posts in boxes.
function addPosts(searchTerm){
  console.log("in " + searchTerm);
  
} 

Thanks!

I’ve edited your post for readability. When you enter a code block into the forum, remember to precede it with a line of three backticks and follow it with a line of three backticks to make easier to read. See this post to find the backtick on your keyboard. The “preformatted text” tool in the editor (</>) will also add backticks around text.

markdown_Forums

@MrGoldPWD,
you have to understand that $.getJSON is asynchronous and does not execute immediately when you are calling it. Without seeing the rest of your code, I am guessing that the function ends before a response is sent back and that is why you are not seeing anything.

Does any other code inside the if block execute like you expect it to ?

edit: if it is an issue of 'asynchronousity ’ as @TomerPacific implies maybe you can just exit out of the key up event if (event.keyCode!== 13) before it gets to the $.getJSON , but without testing the code I can’t really say if what is happening is really due to the asynchronousity issue.

Go into your dev tools and click on the “Network” tab. All of the major browsers have this tab available. Here it is in Chrome

Open the tab and then fire off your event again. If it’s sending a request, you’ll be able to see it here.