0

I've created the code below, but it is not working properly. Where have I gone wrong and or what did I forget to include?

var search = document.getElementById("search").value;
var xhr = new XMLHttpRequest();

function results() {
    console.log(search);
 xhr.send() 
}
document.getElementById("results").innerHTML = results();


// Send the XHR
xhr.open('GET', 'https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search;', true);
<html>
<head>
 <!-- JS -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  
</head>
<body>
<input type="search" id="search" />
<button onclick="results()">Search</button>
<p id="results"></p>

</body>
</html>
chaser7016
  • 597
  • 1
  • 9
  • 28
  • This might be helping http://stackoverflow.com/questions/9713058/sending-post-data-with-a-xmlhttprequest :Let me know if not – rakeeee Apr 11 '15 at 03:40

2 Answers2

1

Your code will run on page-load but you want to create an event listener that waits for your user to press Search and then execute your request.

Try:

$('#search').click(function(){
    var search = document.getElementById("search").value;
    var xhr = new XMLHttpRequest();
    var results = xhr.open('GET', 'https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search;', false);
    document.getElementById("results").innerHTML = results;
})

The 'false' parameter in the xhr request prevents the code from running asynchronously but I am sure you could somehow use callbacks?

oli5679
  • 1,149
  • 1
  • 10
  • 27
0

Figured it out...

function audioResults(){
    var search = document.getElementById("search").value;
    var xhr = new XMLHttpRequest();
    xhr.open('GET', "https://api.soundcloud.com/tracks?client_id=1dff55bf515582dc759594dac5ba46e9&q=" + search, false);
 xhr.addEventListener("load", function() {
  document.getElementById("results").innerHTML = xhr.response;
 }, false);
 xhr.send();
}
<html>
<head>
 <!-- JS -->
  <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
  
</head>
<body>
  
<input type="search" id="search" />
  
<button onclick="audioResults()">Search</button>
  
<p id="results"></p>


</body>
</html>
chaser7016
  • 597
  • 1
  • 9
  • 28