title: API call in Chrome Extension requires two button presses
body: <p>I'm creating a Chrome extension that injects an HTML form on a page through inject.js and when a query is entered and the button is pressed an API call is made through background.js. The contents are then brought back to the inject.js script and processed.</p>
  
  <p>When I first try to make a call through inject.js I get the following error:</p>
  
  <pre><code>    Error in event handler for 'undefined': fetchResult is not defined ReferenceError: searchResult is not defined
  </code></pre>
  
  <p>Oddly enough when I wait a little and press again the query is fetched.</p>
  
  <p>I'm suspecting fetchresult is undefined the first time because it takes a couple of moments to fetch the query but I don't know how to fix this.</p>
  
  <p>inject.js:</p>
  
  <pre><code>    function fetch() {
  
      var fetchResult;
  
      var fetchquery = document.getElementById('field').value;
  
      chrome.extension.sendMessage({greeting: fetchquery}, function(response) {
               fetchResults = response.farewell
              constructHTML(fetchResultsResults)      
  
          });
      };
  </code></pre>
  
  <p>background.js:</p>
  
  <pre><code>    function loadXMLDoc(query)
      {
  
     if (query){
      // new cross origin XML request
  
     xmlhttp=new XMLHttpRequest();
     xmlhttp.onreadystatechange=function()
      {
       if (xmlhttp.readyState==4 &amp;&amp; xmlhttp.status==200)
        {
           fetchResult = JSON.parse(xmlhttp.responseText);
           }
       }
  
     xmlhttp.open("GET","http://XXXXXXXXXXXXXXX&amp;q="+query, true);
     xmlhttp.send();
  
     return fetchResult;
  
     } else {
  
         return "noquery";
      }
      };
  
      chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
         if (loadXMLDoc(request.greeting) != "noquery"){
              sendResponse({farewell: loadXMLDoc(request.greeting)})
              }
      });
  </code></pre>
  
  <p>Any help will be greatly appreciated!</p>