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>
Related
I have this code
<html>
<head>
<script>
function main(){
function loadWordlist(url){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('firstFunction');
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
loadWordlist('https://www.example.com/');
}
main()
</script>
</head>
<body>
<script>
console.log('secondFunction')
</script>
</body>
<html>
Here i am getting the content from the url
And during that the browser contain loading the code and execute it
But i get secondFunction first then firstFunction
And i want firstFunction to execute first then secondFunction after firstFunction finish
Call the second function from the first function.
<html>
<head>
<script>
function main(){
function loadWordlist(url){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('firstFunction');
secondFunction();
}
};
xhttp.open("GET", url, true);
xhttp.send();
}
loadWordlist('https://www.example.com/');
}
main()
</script>
</head>
<body>
<script>
function secondFunction() {
console.log('secondFunction');
}
</script>
</body>
<html>
If that's not possible, you can make xhttp.send() blocking. I strongly advise against it. It's bad user experience. But it's possible, and maybe there are use-cases where this is the only solution.
<html>
<head>
<script>
function main(){
function loadWordlist(url){
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
console.log('firstFunction');
}
};
xhttp.open("GET", url, false);
xhttp.send();
}
loadWordlist('https://www.example.com/');
}
main()
</script>
</head>
<body>
<script>
console.log('secondFunction')
</script>
</body>
<html>
I was wondering what I was doing wrong with this code? I'm trying to get the response for PC players from the API to be set to a tag in the html, but this isn't working.
Code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Battlefield 4 Tracker</title>
<link href="css/bootstrap/bootstrap.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="js/bootstrap/bootstrap.min.js"></script>
<script src="js/jquery-3.1.1.min.js"></script>
</head>
<body>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
var request = new XMLHttpRequest();
var jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
var obj = JSON.parse(jsonResponse);
document.getElementById("response").innerHTML = obj.pc[1].count + "";
</script>
</body>
</html>
Since you are using JQuery as suggested by the html you provided , you can use $.get method of it. This method is a simple wrapper to work with the xmlHTTP asynchronous calls. The success call back of this method is where you should populate the obj with response.
And obj.pc is also an object, so you should access it like obj.pc.count
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Battlefield 4 Tracker</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/css/bootstrap.min.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.0.0-alpha.5/js/bootstrap.min.js"></script>
</head>
<body>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
var request = new XMLHttpRequest();
var obj = null;
var jsonResponse = $.get("http://api.bf4stats.com/api/onlinePlayers", function(response){
obj = response;
document.getElementById("response").innerHTML = obj.pc.count + "";
})
</script>
</body>
</html>
you forgot to send the XMLHttpRequest and what you get back is a object of object so you can call directly obj.pc.count. Try this one:
var json = new XMLHttpRequest();
json.open("GET", "http://api.bf4stats.com/api/onlinePlayers", false)
json.send(null)
var obj = JSON.parse(json.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
You never sent the request. You're missing request.send(). You then listen for the load event, when you've gotten a response.
Here's an edited version of your code. I assumed that you want to loop through all the types of devices and count them.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fullscreen">
<div class="fullscreen-content">
<div id="centered">
<h1>Battlefield 4 Stats Tracker</h1>
<input id="username" name="username" placeholder="PSN Username">
<button id="submit">Submit</button>
<p id="response">
Response goes here.
</p>
</div>
</div>
</div>
<script>
function reqListener () {
//THIS HAPPENS AFTER THE REQUEST HAS BEEN LOADED.
var obj = JSON.parse(this.responseText);
var counter = 0;
for(var k in obj) {
var o = obj[k];
counter += o.count;
}
document.getElementById("response").innerHTML = counter;
}
var request = new XMLHttpRequest();
request.addEventListener("load", reqListener);
request.open("GET", "http://api.bf4stats.com/api/onlinePlayers");
request.send();
</script>
</body>
</html>
You may want to consider other events such as a failed attempt to load the request, etc. Here's more info: https://developer.mozilla.org/en/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest
The request is never send send();
The correct way to do this is to handle it in the onreadystatechange event.
Try this (together with a proper check):
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
myFunction(obj);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
function myFunction(obj) {
document.getElementById("response").innerHTML = obj.pc.count;
}
or directly without extra function:
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
Demo
var xmlhttp = new XMLHttpRequest();
var url = "http://api.bf4stats.com/api/onlinePlayers";
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count;
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
<div id="response"></div>
Try this one :-
<script>
var request = new XMLHttpRequest();
request.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var obj = JSON.parse(this.responseText);
document.getElementById("response").innerHTML = obj.pc.count + "";
}
};
jsonResponse = request.open("GET", "http://api.bf4stats.com/api/onlinePlayers", true);
request.send();
</script>
Is it possible to call a text file similarily to how you would reference an image in a image tag? Similar to
<img src="http://link.to/image.png">
but
<p src="http://link.to/text.txt"></p>
?
Can you do this with javascript? Any advice would be super appreciated!
You can do this with XHR (XMLHttpRequest) . Pure Javascript:
<p id="text"></p>
<script>
text = document.getElementById('text');
xhr = new XMLHttpRequest();
xhr.open("GET", "http://link.to/file.txt");
xhr.send();
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) //the readyState if the status of the request
text.innerHTML = xhr.responseText; // (http://www.w3schools.com/ajax/ajax_xmlhttprequest_onreadystatechange.asp)
// 4 is a completed request
}
</script>
Or, jQuery has the .load() function:
<p id="text"></p>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script>
$('#text').load('http://link.to/file.txt');
</script>
You can load the remote content via AJAX, as long as the remote server sends you proper CORS headers.
Something like this should work:
var $p = document.getElementsByTagName('p')[0];
var url = $p.getAttribute('src');
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function insertContents() {
if (xhr.readyState === 4 && xhr.status === 200) {
$p.innerHTML = xhr.responseText;
}
};
xhr.open('GET', url);
xhr.send();
possible with ajax
<p data-src="http://link.to/text.txt"></p>
JS:
$('p').each(function () {
var $this = $(this);
$.ajax({
url: $this.data('src'),
dataType: "text",
success: function (data) {
$this.html(data);
}
});
});
var client = new XMLHttpRequest();
client.open('GET', 'text.txt');
client.onreadystatechange = function() {
alert(client.responseText);
}
client.send();
You can display text file using IFrame. Like this-
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>
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;
}