I try to get data from the Pixabay service.

The request does not work (server response 0)

JSBin simple example

When in the request parameters I turn off the asynchrony through

xhr.open('GET', URL, false); 

request receives data.

How can I make an asynchronous request correctly?

PS Understood, the code that will be run after an asynchronous operation is performed must be included in the event handler readystatechange

 xhr.onreadystatechange = function() { if (xhr.readyState == 4) { //код } }; 

or alternatively in the load event handler

 xhr.onload = function() { console.log( xhr.responseText ); }; 

    2 answers 2

    I was originally wrong. Headers for cross-domain query is.
    This is how it will work:

     var searchQuery = "flower" var URL = 'https://pixabay.com/api/?key=2668103-5fd953825a02c25d2f0581911&q='+ searchQuery + '&image_type=photo&pretty=true'; var xhr = new XMLHttpRequest(); xhr.open("GET", URL, true); xhr.onreadystatechange = function() { if (xhr.readyState == 4) { console.log( xhr.responseText ); } } xhr.send(); 
    Your mistake was that you tried to output the data before it was received.

      PS Understood, the code that will be run after an asynchronous operation is performed must be included in the event handler readystatechange

       xhr.onreadystatechange = function() { if (xhr.readyState == 4) { //код } }; 

      or alternatively in the load event handler

       xhr.onload = function() { console.log( xhr.responseText ); };