JSON AJAX Http request - javascript

I am working with a JSON file that I have, and I am linking it in my JavaScript.
I am trying to get it requested through AJAX to show up on my console.log, but I am just getting null for my readystatechange function. What am I doing wrong?
Also to better clarify I am doing this for my course and ideally what my goal is; I have a json file that I created (myjson.com), I have that URL its in my JavaScript, and I am trying to get that json url to update to my JavaScript so when I do a console.log it shows up the values of the objects from the json. Here's my code:
<div id="btn1"> Update </div>
<div id="output"></div>
<script>
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = newXMLHttpRequest();
a.onreadystatechange = function () {
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
</script>
UPDATE
Code from the comment:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(this.readyState == 4) {
var myObj = this.responseText;
}
console.log(a);
}
a.open("GET", "api.myjson.com/bins/z79bt";, true);
a.send();
};

Two issues:
you're missing a space in newXMLHttpRequest
you're not doing anything inside the state change callback
(third: you're also not populating the output div)
See the live example here:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(a.readyState === XMLHttpRequest.DONE && a.status === 200) {
console.log(a.responseText);
output.textContent = a.responseText;
}
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
<div id="btn1"> Update </div>
<div id="output"></div>
UPDATE
Fixed code from the comment:
var output = document.getElementById("output");
document.getElementById("btn1").onclick = function () {
var a = new XMLHttpRequest();
a.onreadystatechange = function () {
if(this.readyState == 4) {
var myObj = this.responseText;
console.log(myObj);
}
}
a.open("GET", "https://api.myjson.com/bins/z79bt", true);
a.send();
};
<div id="btn1"> Update </div>
<div id="output"></div>

Related

xmlHTTPRequests code not working to fetch json from jsonbin

I am going to fetch a json file from jsonbin when clicking a button, but it is not working, your help is appreciated.
<button id="runxhr">RUN XHR</button>
<div id="main"></div>
js file is here:
function runXHR() {
let xhr = new XMLHttpRequest();
addListeners(xhr);
xhr.open(
"GET",
"https://api.jsonbin.io/v3/b/62b4395c449a1f3821167058/",
true
);
xhr.setRequestHeader("X-Bin-Meta", "false");
xhr.send();
return xhr.responseText;
}
function addListeners(xhr) {
xhr.addEventListener("loadend", display(xhr));
}
function display(jsonstring) {
let main = document.getElementById("main");
json = JSON.parse(jsonstring);
main.innerHTML = json[0]["name"];
}
const buttnRun = document.getElementById("runxhr");
buttnRun.addEventListener("click", () => {
runXHR();
});
JSONBin author here. You are doing several things wrong in the above example so I just refactored your code in general. Here's how you could fetch the JSON and print the body on click of a button.
To enhance it further, I have replaced your div tag with a pre tag, and I am using JSON.stringify() to pretty print the JSON to make it readable.
let btn = document.getElementById('runxhr');
btn.addEventListener('click', () => {
let req = new XMLHttpRequest();
req.onreadystatechange = () => {
if (req.readyState == XMLHttpRequest.DONE) {
document.getElementById('main').innerText = JSON.stringify(JSON.parse(req.responseText), null, 2);
}
};
req.open("GET", "https://api.jsonbin.io/v3/b/62b4395c449a1f3821167058/", true);
req.setRequestHeader("X-Bin-Meta", false);
req.send();
})
<button id="runxhr">Run XHR</button>
<pre id="main"></pre>

Parsing JSON Array to print specific elements

Im currently trying to parse JSON data from this api in JS but im not sure how to. As of right now when I press any buttons to give me the data, it prints the arrays out rather than the specific data I want. Ive tried to use the JSON Parse function to retrieve the specific data but it seems its not working. Any help would be greatly appreciated! URL to the API docs: https://www.balldontlie.io/#get-all-players
//Loads Player Data
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("players").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
var data = JSON.parse(xhttp.responseText);
console.log(data["last_name"])
xhttp.send();
}
//Loads Game Data
function loadGames() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("games").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/games", true);
xhttp.send();
}
//Loads Team Data
function loadTeams() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("teams").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/teams", true);
xhttp.send();
}
<!DOCTYPE html>
<html>
<body style="background-color:peachpuff;" >
<center>NBA STATS</center>
<center><marquee behavior="scroll" direction="right" scrollamount="12.5">Data Extracted From BDL API</marquee></center>
<center> View API Docs </center>
<script src="main.js"></script>
<div id="players">
<button type="button" onclick="loadPlayers()">View Players</button>
</div>
<div id = "teams" >
<button type="button2" onclick="loadTeams()">View Teams</button>
</div>
<div id ="games">
<button type="button3" onclick="loadGames()">View Games</button>
<div>
</body>
</html>
You should parse JSON in xhttp.onreadystatechange, that's a callback when request data success.
For the players data as example, it is an object with data and meta, and the players is in data key which is an Array, so you need to loop inside the array to print the values that you needed.
Here's the example for loadPlayers(). You can apply the same concept to loadGames and loadTeams, please let me know if you still having questions.
function loadPlayers() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
// parse JSON after response
var players = JSON.parse(this.responseText);
// get 'data' key inside response
var playersData = players.data;
// loop all the players
for (var player of playersData) {
// print last_name to the #players element
document.getElementById("players").innerHTML += "<br />" + player['last_name'];
}
}
};
xhttp.open("GET", "https://www.balldontlie.io/api/v1/players", true);
xhttp.send();
}
In function loadPlayers()
data is an array not object

JavaScript Handlebars give no error but does not work

I am trying to replace text in my page using handlebars. But its not working and i am not getting any errors either.
The following code kicks in when the user presses the submit button
<button type="submit" id="add_lunch" class="button button-contactForm boxed-btn" onclick="addToCart()">Submit</button>
this then
function addtoCart() {
var request = new XMLHttpRequest();
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = $("input[name='dessert_id']:checked").val();
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var template = Handlebars.compile(document.querySelector('#js_result').innerHTML);
var data_response = JSON.parse(request.responseText);
var content = template({'base_name': data_response.base.name});
console.log("****" + data_response.base.name)
document.addEventListener('DOMContentLoaded', () => {
document.querySelector('#add_lunch').onclick = () => {
document.querySelector('#media_js_body').innerHTML += content;
};
});
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
return false;
}
plus the template
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/4.0.11/handlebars.min.js"></script>
<script id="js_result" type="text/x-handlebars-template">
{{ base_name }}
</script>
<script src="{{ url_for('static', filename='js/util.js') }}"></script>
What i have figured out so far is that it has something to do with DOM state? and onclick even.
Any suggestions and corrections?
i do not know if it was the coffee i drank, but after a few sips and few changes it seems to work partially now. i am getting the text being placed in the right place.
Now i only have to make sure that the values from data_response gets transferred in content as well
This is what i changed.
function addToCart() {
var request = new XMLHttpRequest();
var limit=2;
var base_id = $("input[name='base_id']:checked").val();
var protein_id = $("input[name='protein_id']:checked").val();
var dessert_id = $("input[name='dessert_id']:checked").val();
var side_id = [];
$.each($("input[name='side_id']:checked"), function(){
side_id.push($(this).val());
});
if(side_id.length==limit) {
request.open('POST', '/cart');
request.onload = () => {
// Extract JSON data from request
var data_response = JSON.parse(request.responseText);
var templateInfo=document.querySelector('#js_result').innerHTML
console.log("TempInfo:" + templateInfo)
var template = Handlebars.compile(templateInfo);
var content = template({'base_name': data_response.base.name});
console.log("DataResponse:" + data_response.base.name);
console.log("Content:" + data_response.base.name);
document.querySelector('#media_js_body').innerHTML += content;
}
var data = new FormData();
data.append('base_id', base_id);
data.append('protein_id', protein_id);
data.append('side_id', side_id);
data.append('dessert_id', dessert_id);
// Send request
request.send(data);
} else {
alert("Kindly select "+limit+" sides")
}
return false;
}

How To Pull Multiple JSON records with one search

In the current DEMO you can search one thing at a time.
If you search either values (1001, 1002, 1003) and a JSON property feature will be pulled.
So if I search: 1001
I get: RANK_BY_CD: 26
I've tired a fuzzy-search library - http://fusejs.io/ but I don't think what is needed since I need a series of EXACT matches
var data = [];
$(document).ready(function () {
$("#button").click(function (any_function_variable_name) {
var searchId = String($('#searchBox').val());
data.features.forEach(function (any_function_variable_name) {
if (any_function_variable_name.properties.CDUID == searchId) {
$("ul")
.append('<li> <strong>RANK_BY_CD: </strong>' + any_function_variable_name.properties.RANK_BY_CD);
}
});
});
});
function getdata() {
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/6oj58";
//var data = [];
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
getdata();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="searchBox" type="text"></textarea>
<button id="button">
Search
</button>
<div>
<ul></ul>
</div>
I want to have the ability to copy paste multiple strings (separated by line break) into the textarea like so:
1001
1002
1003
and get:
RANK_BY_CD: 26
RANK_BY_CD: 212
RANK_BY_CD: 248
Also, I don't want the code to just be limited to these 3 options.
As JSON file gets bigger I want to recognize all the CDUIDs
So a key legend will be inefficient in this case
This is the external JSON file url - https://api.myjson.com/bins/6oj58
You can create a Set which stores the list of ids and then check that against the CDUID of each item in data.features:
var data = [];
$(document).ready(function () {
$("#button").click(function (any_function_variable_name) {
var searchIds = new Set($('#searchBox').val().split(',').map(s => s.trim()));
data.features.forEach(({ properties: { CDUID, RANK_BY_CD } }) => {
if (searchIds.has(CDUID)) {
$("ul")
.append(`<li> <strong>RANK_BY_CD: </strong>${RANK_BY_CD}`);
}
});
});
});
function getdata() {
var xmlhttp = new XMLHttpRequest();
var url = "https://api.myjson.com/bins/6oj58";
//var data = [];
xmlhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
data = JSON.parse(this.responseText);
}
};
xmlhttp.open("GET", url, true);
xmlhttp.send();
}
getdata();
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<textarea id="searchBox" type="text"></textarea>
<button id="button">
Search
</button>
<div>
<ul></ul>
</div>

Javascript i can't add a new paragraph using ajax

Hi im having this problem, when i use the code only for the (without the "demo2" ) works fine, and in the browser i can see the text that its on "PruebasGeneral/MBVR000008.txt" and when i change this file/text, works in my HTML without refreshing, but i need to add another as you can see, i tried to add in the same function, but doesnt work, with this code in the browser in the two paragraph shows whats inside "PruebasGeneral/MBVR000009.txt" so basically shows demo2 and demo2. WHAT SHOULD I DO?
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<p id="demo2"></p>
<script>
function loadDoc(path, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.responseText);
}
};
xhttp.open("GET", path + "?t=" + Math.random(), true);
xhttp.send();
}
function data1Loaded(data) {
document.getElementById("demo").innerHTML = data ; // do something with data
}
function data2Loaded(data) {
document.getElementById("demo2").innerHTML = data ; // do something with data
}
function loadDocs() {
loadDoc('/PruebasGeneral/MBVR000008.txt', data1Loaded);
loadDoc('/PruebasGeneral/MBVR000009.txt', data2Loaded);
setTimeout(loadDocs, 1000);
}
window.onload = loadDocs;
</script>
</body>
</html>
You need to have all of that over again. You can't just call open() twice:
function loadDoc(path, callback) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
callback(this.responseText);
}
};
xhttp.open("GET", path + "?t=" + Math.random(), true);
xhttp.send();
}
function data1Loaded(data) {
// do something with data
}
function data2Loaded(data) {
// do something with data
}
function loadDocs() {
loadDoc('path1', data1Loaded);
loadDoc('path2', data2Loaded);
setTimeout(loadDocs, 1000);
}
window.onload = loadDocs;

Categories