SoundCloud: Search & display results using Javascript - javascript

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>

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?

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>

Related

AJAX Get Request Button

I want when I click the button a GET Request to send but I don't know how to connect the AJAX script with the button.
<script>
var url = "http://myurl.com";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
</script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button>Make a request</button>
you need transform it in a function and call by the button:
<script>
function call()
{
var url = "http://myurl.com";
var xhr = new XMLHttpRequest();
xhr.open("GET", url);
xhr.onreadystatechange = function () {
if (xhr.readyState === 4) {
console.log(xhr.status);
console.log(xhr.responseText);
}};
xhr.send();
}
</script>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button onclick="call();">Make a request</button>
Seeing as you are importing Jquery, there is also a helper function to fetch data from an AJAX request, you can use it like this:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
</head>
<button>Make a request</button>
<!-- Javascript -->
<script>
$('button').click(function(){
$.get("http://myurl.com", function(result) {
console.log(result);
});
});
</script>

TypeError: Cannot read property 'src' of null at XMLHttpRequest.xhr.onreadystatechange

Hi i am new in web development, i am trying to hit an random image url generator API and trying to show image on screen.
i am getting the response from API but while passing the url to img variable i am getting TypeError: Cannot read property 'src' of null at XMLHttpRequest.xhr.onreadystatechange
<html>
<head>
<script>
var btn = document.querySelector("#btn");
var img = document.querySelector("#photo");
function c(){
var xhr = new XMLHttpRequest(),
method = "GET",
url = "https://dog.ceo/api/breeds/image/random";
xhr.open(method, url, true);
xhr.onreadystatechange = async function () {
if(xhr.readyState === 4 && xhr.status === 200) {
var url = JSON.parse(xhr.responseText).message;
img.src == url; <!-- I am getting error at this line-->
}
};
xhr.send();
}
</script>
<link rel="stylesheet" type="text/css" href="Dog app.css">
</head>
<body>
<div class="container">
<h1>Welcome to dog photo app</h1>
<img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" id="photo" alt=""><br>
<form>
<input type="button" id="btn" onclick="c()" value="click me">
</form>
</div>
</body>
</html>
<html>
<head>
<script>
function c(){
var btn = document.querySelector("#btn");
var img = document.querySelector("#photo");
var xhr = new XMLHttpRequest(),
method = "GET",
url = "https://dog.ceo/api/breeds/image/random";
xhr.open(method, url, true);
xhr.onreadystatechange = async function () {
if(xhr.readyState === 4 && xhr.status === 200) {
var url = JSON.parse(xhr.responseText).message;
img.src = url; <!-- I am getting error at this line-->
}
};
xhr.send();
}
</script>
<link rel="stylesheet" type="text/css" href="Dog app.css">
</head>
<body>
<div class="container">
<h1>Welcome to dog photo app</h1>
<img src="https:\/\/images.dog.ceo\/breeds\/waterdog-spanish\/20180723_185544.jpg" id="photo" alt=""><br>
<form>
<input type="button" id="btn" onclick="c()" value="click me">
</form>
</div>
</body>
</html>
Just replacethe == with = while assigning url to img
and move
var btn = document.querySelector("#btn");
var img = document.querySelector("#photo");
inside the c() function and it will work
You executed var img = document.querySelector("#photo"); before the image existed in the HTML. (It is defined below your JS code.
Moving the declarations of btn and img inside function c() { ... } will fix your issue, because all the HTML elements will exist.
function c(){
// Declarations have been added here
var btn = document.querySelector("#btn");
var img = document.querySelector("#photo");
// Rest of the code
var xhr = new XMLHttpRequest(),
// ...
You typed
img.src == url;
If you want to assign the value of url to img.src, use only one = sign. == would mean checking if the value of img.src and url are the same. #HeySora's answer is also relevant; you need the script to run after the html element exists.

Onloading webpage spinner (loading) doesn't stop in the browser tab?

On loading webpage the spinner should stop in browser but it doesn't it keeps on spinning how can I stop this.
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
</head>
<body>
<script type="text/javascript">
var requestURL = "https://newsapi.org/v1/articles?source=techcrunch&sortBy=top&apiKey=045089075bc74354be01b34f6335d32b";
var request = new XMLHttpRequest();
request.open('GET',requestURL);
request.responseType = 'json';
request.send();
request.onload = function() {
var myjsondata = request.response;
console.log(myjsondata);
showdata(myjsondata);
}
function showdata (data) {
var str = data.articles[0].title;
document.write(str + "<br> <br>");
var img = data.articles[1].description;
document.write(img);
}
</script>
</body>
</html>
You can check this image ->

How to use XHR in pop up window

Hi I need to know how to read a API from pop up window.
Here is my popup window
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="test.js"></script>
</head>
<body>
<b>Enter your Email ID and Password</b><br><br>
<form id="userinfo">
<label for="user"> Email : </label>
<input type="text" id="user" /><span id="semail"></span>
<br><br>
<label for="pass">Password : </label>
<input type="password" id="pass" />
<br>
<br>
<input type="button" id="login" value="Log In"/>
</form>
</body>
</html>
Here is my test.js
window.addEventListener('DOMContentLoaded', function() {
var user = document.querySelector('input#user');
var pwd = document.querySelector('input#pass');
var login = document.querySelector('input#login');
login.addEventListener('click', function() {
var userStr = user.value;
var pwdStr = pwd.value;
var req = getHTTPObject();;
var url="http://blog.calpinetech.com/test/index.php";
req.open("GET", url);
req.send(null);
if (req.status == 200) {
var item=req.responseText;
alert(item);
}
window.close();
chrome.runtime.getBackgroundPage(function(bgPage) {
bgPage.updateIcon();
});
});
});
Here when I click on the log in button it has to read the API(server file named "http://blog.calpinetech.com/test/index.php"). How can I do it?Please help me
Btw, Any reason of not using XMLHttpRequest to make AJAX calls ?
Sample in your event listener could be helpful:
var userStr = user.value,
pwdStr = pwd.value,
url="http://blog.calpinetech.com/test/index.php";
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
}
else if (window.ActiveXObject) {
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlHttpReq.open('POST', url, true);
xmlHttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlHttpReq.send("username="+userStr+"&passwd="+pwdStr);
/** Handle your response here */

Convert API request to text to use in site

I am trying to make an API request and put the return in a div.. What am I doing wrong?
<!DOCTYPE HTML>
<html>
<head>
<script>
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", false);
xhr.send();
xhr = function() {
document.getElementById("myDiv").innerHTML=xhr.responseText;
}
</script>
</head>
<body>
<div id="myDiv"></div>
</body>
</html>
You need to bind onto the onload listener instead of setting a value to xhr:
var xhr = new XMLHttpRequest();
xhr.open("GET", "http://data.mtgox.com/api/2/BTCUSD/money/ticker_fast?pretty", false);
xhr.onload = function() {
document.getElementById("myDiv").innerHTML=this.responseText;
};
xhr.send();
See the MDN docs on Using XMLHttpRequest.
You need
xhr.onload = function() { //onload
document.getElementById("myDiv").innerHTML=xhr.responseText;
}

Categories

Resources