How To Pull Multiple JSON records with one search - javascript

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>

Related

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

How to parse json using ajax script in ESP32 app

I am working on a project using ESP32, I get some data from some sensors and send it to a webpage hosted in the same board.
I read some info on the web and understood that is "better" to send all data from several sensors using json method, so my function to get and send data is this:
void handle_leituras()
{
String results_json = "{ \"data\": " + Data +
"," + "\"hora\": " + Hora +
"," + "\"temp_amb1\": " + Tout + " }";
server.send(200, "application/json", results_json);
}
Testing above function in serial monitor I have this data:
{"data": Domingo, 12/4/2020,"hora": 20:53,"temp_amb1": 25.75}
I found a script that can get only one data and print it on that page, this is the script:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("DATA").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "leituras", true);
xhttp.send();
}
Its my index page code that shows data on webpage:
const char pag_inicial[] PROGMEM = R"=====(
<!DOCTYPE html>
<head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0, user-scalable=no\">
<title>My 1st test</title></head>
<html>
<body>
<div id="pagina">
<h1>System XPTO</h1>
<div>
Data: <span id="DATA">ND</span><br>
Hora: <span id="HORA">ND</span><br>
Temperatura Ambiente: <span id="TEMPAMB1">ND</span>
</div>
<div id="botoes">
<button type="button" onclick="sendData(0)" style="width: 80px; height: 30px; margin: 30px;">ON</button>
<button type="button" onclick="sendData(1)" style="width: 80px; height: 30px; margin: 30px;">OFF</button><BR>
</div>
<script>
setInterval(function() {
// Call a function repetatively with 1 Second interval
getData();
}, 1000); //2000mSeconds update rate
//function to set on / off a LED on my board
function sendData(led) {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("LEDState").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "setLED?LEDstate="+led, true);
xhttp.send();
}
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
</script>
</div>
</body>
</html>
)=====";
My problem is...I don't know how to modify this script to get more sensors values from the described above function.
Anybody can save me please?
Thanks in advance ;)
The standard XMLHttpRequest only supports responseText and responseXML, it does not support responseJSON property. However, as long as your server is sending a valid serialised JSON string, the responseText should contain the JSON code as text, so all you've got to do is to parse it with JSON.parse(), and then you can access each JSON element with dot notation:
function getData() {
var xhttp = new XMLHttpRequest();
xhttp.open("GET", "leituras", true);
xhttp.send();
xhttp.onload = function() {
if (this.status == 200) {
var jsonResponse = JSON.parse(this.responseText);
document.getElementById("DATA").innerHTML = jsonResponse.data;
document.getElementById("HORA").innerHTML = jsonResponse.hora;
document.getElementById("TEMPAMB1").innerHTML = jsonResponse.temp_amb1;
}
else {
console.log(this.status);
}
};
}
This piece of code works for all browsers that supports XMLHttpRequest and JSON as long as the server is sending a valid JSON object.

How to search for items in a list in javascript?

I have a requirement to search github API for fetching repositories or users and display it.
I have tried the below code, but cannot able to filter by name from API.
Can someone help on this?
var searchValue = document.getElementById("search").innerHTML;
function UserAction() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert(this.responseText);
//Show the name based on filter
if (searchValue.toUpperCase().indexOf(filter) > -1) {
//display the list of users below
}
}
};
xhttp.open("GET", "https://api.github.com/search/repositories?q="+searchValue, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
Search Repo..<input type="text" name="search" id="search" placeholder="Search for names.." onkeyup="UserAction()" />
I'm expecting an output like below in pure javascript, strictly no jquery or any other frameworks.
Can someone help on this?
First you need to retrieve the value from the input after it's been typed in. Right now you're just getting the undefined value.
Once you have that, you need to parse the response from GitHub into an object, look for the parts of the response you are interested in, and compare to your filter.
Here we compare the search term to the repo name and the owner login. I've also added some rudimentary debounce code, you might be able to come up with something more robust with some work. There's no error checking here, which you'll probably want, and I'm just dumping the output into a div — you'll probably want to style that.
Hopefully that will give you enough to get started.
var debounceInterval
var debounceWaitTime = 200 // ms
// simple debounce
function UserAction() {
clearInterval(debounceInterval)
debounceInterval = setTimeout(sendRequest, debounceWaitTime)
}
function sendRequest() {
let out = document.getElementById('output')
out.innerHTML = ''
// you need to get this value here, not just once at the beginning
var searchValue = document.getElementById("search").value;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
let resObj = JSON.parse(this.responseText);
//Show the name based on filter
resObj.items.forEach(item => {
// look in full_name and owner.login for searchValue
if (item.full_name.toUpperCase().includes(searchValue.toUpperCase())
|| item.owner.login.toUpperCase().includes(searchValue.toUpperCase())) {
out.innerHTML += "Repo: " + item.full_name + ' Owner: ' + item.owner.login + '<br>'
}
})
}
};
xhttp.open("GET", "https://api.github.com/search/repositories?q=" + searchValue, true);
xhttp.setRequestHeader("Content-type", "application/json");
xhttp.send("Your JSON Data Here");
}
Search Repo..<input type="text" name="search" id="search" placeholder="Search for names.." onkeyup="UserAction()" />
<hr />
<div id="output">

JSON AJAX Http request

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>

AJAX and datalists

I'm trying to use XML to get a list of cities from a website, then go through and add each of the cities to a datalist so that when I put in an input it will filter the cities in the list.
example of city list:
Aleppo
Alexandria
Alger
Almaty
Ankara
Anshan
Baghdad
Baku
Bandung
Bangalore
Bangkok
Barcelona
*[Each city name is on a new line]
current html:
<div id="namearea">
<h2>City Name:</h2>
<div>
<input id="citiesinput" list="cities">
<datalist id="cities"></datalist>
<button id="search">
Search
</button>
<span class="loading" id="loadingnames">
Loading...
</span>
</div>
</div>
current JS code:
window.onload = function() {
var request = new XMLHttpRequest();
request.onload = processCities;
request.open("GET", "url", true);
request.send();
};
Inspecting the page with Firebug shows that nothing is being added to the datalist, so I'm wondering what I'm doing wrong. I also tried using .responseText rather than .responeXML but it didn't make any difference.
[Fixed]
I changed the processCities() function to:
function processCities() {
var response = this.responseText;
var city = response.split("\n");
var options = "";
for(var i = 0; i < response.length; i++) {
options += "<option value='"+city[i]+"'>\n";
}
document.getElementById("cities").innerHTML = options;
}
This code seems to work.
Here is an example of making the request. If you really are getting XML, you'll have to parse it. It's better if you could get json.
var request = new XMLHttpRequest();
request.open('GET', '/my/url', true);
request.onload = function() {
if (request.status >= 200 && request.status < 400) {
// Success!
var data = JSON.parse(request.responseText);
} else {
// We reached our target server, but it returned an error
}
};
request.onerror = function() {
// There was a connection error of some sort
};
request.send();

Categories