I am calling a REST API
from this HTML
form
<form action="#">
<h1>Enter your zip code</h1>
<div class="form-group">
<label for="zip">Zip Code</label>
<input type="text" id="zip">
</div>
<div class="button-holder">
<button class="btn btn-primary" onclick="callREST()">Next</button>
</div>
</form>
My API structure looks like this
{
"Agents":
{
"@ZipCode": "33176",
"Agent": [
{
"AgencyID": "21",
"Name": "Anakarina Callejas",
"Phone": "305-515-5613",
"CityName": "KENDALL",
"Address": "10471 N Kendall Dr. #101. Miami, FL 33176",
"Reviews-Rating": "5",
"Reviews-Count": "74",
"image": "/images/agents/21.png"
},
{
"AgencyID": "116",
"Name": "Tamara Mourino",
"Phone": "305-256-0616",
"CityName": "PINECREST",
"Address": "12745 South Dixie Highway. #101. Pinecrest, FL 33156",
"Reviews-Rating": "5",
"Reviews-Count": "70",
"image": "/images/agents/116.png"
}]
}
}
and this is how i am calling the API
function callREST() {
// Create a request variable and assign a new XMLHttpRequest object to it.
var request = new XMLHttpRequest();
// Open a new connection, using the GET request on the URL endpoint
request.open('GET', 'URL to the API', true);
request.onload = function () {
// Begin accessing JSON data here
var responseData = JSON.parse(this.response);
var data = responseData.Agents.Agent;
if (request.status >= 200 && request.status < 400) {
data.forEach(agent => {
// Log each agent's title
console.log(agent.Name);
});
} else {
console.log('error');
}
}
// Send request
request.send();
}
I get all the data but what i need is only the data that matches the ZIP Code
entered in the input field
You can get @ZipCode value from
Agents
object and compare with theinput value
.Here is the working snippet that display the
alert
ifinput value
is matched with sample data'zipCode
value.Note: From comments it is still confusing that how your
response
object can have multiple zipCode.