call rest api and display result as searched for - javascript

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 the input value.
var responseData =JSON.parse(jsonResponse);
var zipCode= responseData.Agents['#ZipCode'];
Here is the working snippet that display the alert if input value is matched with sample data' zipCode value.
var jsonResponse='{"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"}]}}';
function callREST() {
event.preventDefault();//for demo to prevent form submit.
var inputZip=document.getElementById("zip").value;
var responseData =JSON.parse(jsonResponse);
var zipCode= responseData.Agents['#ZipCode'];
//console.log(inputZip,zipCode);
if(zipCode==inputZip){
alert("ZipCode matched.");
}else{
alert("ZipCode not matched.");
}
}
<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>
Note: From comments it is still confusing that how your response object can have multiple zipCode.
#Comment- Look at your code responseData.Agents.Agent responseData is an object, Agents is an object, how there can be multiple Agents objects in an object. Or even how can be multiple ZipCode prpertirs in Agents object

Related

How to send JSON request with javascript and receive it in Flask?

I've written a form that has a n amount of steps, and after parsing the data into string object (to put inside the request body) inside JavaScript, I want to load it up and send it to my Flask backend server.
{
"0": {
"function": "go_to_url",
"values": {
"url": "https://valid.url/"
}
},
"1": {
"function": "refresh",
"values": {
"amount": "5"
}
},
"2": {
"function": "take_screenshot",
"values": {
"name": "screenshotname"
}
},
"3": {
"function": "send_keys_to_element",
"values": {
"xpath": "//*[#value='login']",
"keysToSend": "loginname"
}
},
"4": {
"function": "assert_element_exist",
"values": {
"xpath": "//button[#login]"
}
}
}
This is what I want to send with onclick function within a button inside mentioned form. My Js call looks like this
function submitScenario() {
const steps = Array.from(document.getElementsByClassName('scenario-creation-step'));
const data = {};
for (const c in steps) {
var currentStep_dict = {};
currentStep_dict['function'] = steps[c].childNodes[0].value;
let inputs = Array.from(steps[c].childNodes[1].getElementsByTagName('input'));
var values = {};
for (const i in inputs) {
values[inputs[i].getAttribute('data')] = inputs[i].value;
}
currentStep_dict['values'] = values;
data[c] = currentStep_dict;
}
var dataJson = JSON.stringify(data);
console.log(dataJson);
fetch(window.location.href + 'ed',
{
method: 'POST',
headers: {
'Content-Type':'application/json',
},
body: dataJson,
}
);
}
The form presents itself like that, with url set for 'scenario_added'
<form action="{{ url_for('scenario_added') }}" method="post" name="scenarioForm">
<!-- inputs hidden for data being fetched from flask -->
<input type="hidden" id="scenario_name" value="{{ scenario_details[0] }}" />
<input type="hidden" id="expected" value="{{ scenario_details[1] }}" />
<input type="hidden" id="author_id" value="{{ scenario_details[2] }}" />
<input type="hidden" id="steps_to_show" value="{{ step_names }}" />
<div id="scenario-creation-table" class="scenario-creation-table">
<button type="button" id="add_step">Add a step</button>
<!-- steps show here -->
</div>
<div class="scenario-creation-submitbuttons">
<div></div>
<div></div>
<input type="button" id="download_json" value="Pobierz scenariusz">
<input type="submit" id="submit_scenario_button" value="Dodaj Scenariusz" onclick="submitScenario()">
</div>
The view for scenario_added looks as follows:
#app.route("/scenario_added", methods = ["GET", "POST"])
def scenario_added():
if request.method == "GET":
return '<h6>bad request, it was get for /scenario_added</h6>' #TODO 404
scenario_data = request.json
return render_template('scenario_added.html', data = scenario_data)
Unfortunately, after sending such request, I'm presented with "Bad Request
Did not attempt to load JSON data because the request Content-Type was not 'application/json'."
Even though, when I send the request via POSTMAN on the url, I receive a 200 Code with expected result of the html view containing the data.
How should I rearrange the form or JavaScript function so it will send a request with data gathered from the form?

How to use html form to submit API link to get JSON response

I am creating a Package Tracking Form for a courier company.
Here is my html form
<h2>Track Package</h2>
<form>
<label for="trackingno">Tracking No:</label>
<input type="tel" id="trackingno" name="trackingno">
<input type="submit" value="Submit">
</form>
Company has provided the API Link
http://portal.activecourier.pk/api/v1/packet/00003711/status
When I click this link I get this data
{"packet_id": "0024-00003711", "consignee_name": "Nasir maqbool", "destination": "Lahore", "current_status": {"status": "Assigned to Courier", "datetime": "2020-12-27T17:55:05.414Z", "comment": null}, "statuses": [{"status": "Pickup request sent", "datetime": "2020-12-27T09:55:41.295Z", "comment": null}, {"status": "Booked", "datetime": "2020-12-26T10:13:15.333Z", "comment": null}]}
I want to use html form so visitor enters his package tracking # and get his package details
They usually use jquery to do this
$('#submit').click(function() {
const response = $('#response');
const trackingId = $('#trackingId').val();
let html = '';
$('#trackingId').val('');
response.html('Please Wait');
$.get('http://portal.activecourier.pk/api/v1/packet/'+trackingId+'/status', function(data) {
html += '<div><strong>Packet Id:</strong> '+data.packet_id+'</div>';
html += '<div><strong>Consignee Name:</strong> '+data.consignee_name+'</div>';
html += '<div><strong>Current Status:</strong> '+data.current_status.status+' at '+data.current_status.datetime+'</div>';
let statuses = data.statuses.map((e) => {
return e.status + ' at ' + e.datetime
});
html += '<div><strong>Statuses:</strong> <ul><li>'+statuses.join('</li><li>')+'</li></ul></div>';
response.html(html);
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="response"></div>
<input type="text" id="trackingId"/>
<button type="button" id="submit">Submit</button>

Unable to link backend post api with frontend submit button

I am trying to make a zomato random restaurant generator, so whenever you put your city it gives a random restaurant in that city. I made api for it and it works perfectly, this is a sample output of the api call
{
"name": "Natural Ice Cream",
"url": "https://www.zomato.com/ncr/natural-ice-cream-rajouri-garden-new-delhi?utm_source=api_basic_user&utm_medium=api&utm_campaign=v2.1",
"location": {
"address": "J 2/10, BK Dutt Market, Rajouri Garden, New Delhi",
"locality": "Rajouri Garden",
"city": "New Delhi",
"city_id": 1,
"latitude": "28.6474674597",
"longitude": "77.1195488423",
"zipcode": "",
"country_id": 1,
"locality_verbose": "Rajouri Garden, New Delhi"
},
"price": 1,
"thumbnail": "https://b.zmtcdn.com/data/pictures/8/313368/da7c191473cdc9701aa97a8cbcd51255.jpg?fit=around%7C200%3A200&crop=200%3A200%3B%2A%2C%2A",
"rating": "4.7"
}
the backend linking frontend to backend looks like this
searchForm.addEventListener('submit', async e => {
e.preventDefault();
resultArea.innerHTML = '';
const query = e.target.querySelector('#restaurant-name').value;
if (query === '') {
return
}
e.target.querySelector('#restaurant-name').value = '';
const res = await fetch(`${hostname}/locations/${query}`, {
headers: {
"Content-Type": "application/x-www-form-urlencoded",
},
method: 'POST',
})
const json = await res.json();
populateData(json);
});
function populateData(results) {
results.forEach(result => {
const newResult = rTemp.content.cloneNode(true);
newResult.querySelector('.result-title').innerText = result.name;
newResult.querySelector('.result-neighborhood').innerText = result.location.locality;
newResult.querySelector('.result-address').innerText = result.location.address;
newResult.querySelector('.result-price').innerText = '$'.repeat(result.price);
newResult.querySelector('.result-thumbnail').src = result.thumbnail;
newResult.querySelector('.result-website').href = result.url;
resultArea.appendChild(newResult);
});
}
here rTemp is querySelector('template') and resultArea is querySelector('#restaurant-results') and hostname is this.location.origin
And lastly this is the frontend
<body>
<div class="wrapper">
<main>
<h1>Restaurant <span>Random</span></h1>
<form action="">
<div class="form-wrapper">
<label for="restaurant-name">Search</label>
<input name="restaurant-name" type="text" id="restaurant-name" placeholder="City Name">
</div>
<input type="submit">
</form>
</main>
<hr>
<section id="restaurant-results">
</section>
</div>
<template>
<div class="result-card">
<div class="result-header">
<h2 class="result-title">${title}</h2>
<h3 class="result-location result-neighborhood">${neighborhood}</h3>
<h3 class="result-location result-address">${address}</h3>
<p class="result-price">${price}</p>
</div>
<div class="result-body">
<img src="" alt="restaurant-photo" class="result-thumbnail">
</div>
<div class="result-footer">
<button class="result-footer-button">Call</button>
<button class="result-footer-button">Visit Website</button>
<button class="result-footer-button">Make Reservation</button>
</div>
</div>
</template>
<script src="index.js"></script>
</body>
When I run this I get the following error
POST http://127.0.0.1:5500/locations/delhincr 405 (Method Not Allowed)
(anonymous) # index.js:16
index.js:16 is
const res = await fetch(`${hostname}/locations/${query}`, {
and
Uncaught (in promise) SyntaxError: Unexpected end of JSON input
at HTMLFormElement. (index.js:22) which is
const json = await res.json();
I am unable to locate the error. How do I solve these?

Display radio button data from array value in scope angular

I have web service call. I am getting response from webservice like this :
var SSOUserResponse = [
{
"UserName": "se",
"FirstAndLastName": "Sam ",
"EmailAddress": "segfgf#x.net"
},
{
"UserName": "se2",
"FirstAndLastName": "Joe ", //
"EmailAddress": "se266#gmail.com" //
}
];
or
SSOUserResponse array length can me more also.
$scope.launchArray = [];
I want to display this data in my templete.
What I am doing :
if (SSOUserResponse.length > 1) {
var launchArrayVal = [];
for (var i = 0; i < SSOUserResponse.length;i++){
launchArrayVal.push(
{ name: SSOUserResponse[i].UserName, email: SSOUserResponse[i].EmailAddress }
);
$scope.launchArray = launchArrayVal;
}
}
I have a templete :
<div class="modal-body">
<div>Please select an one data</div>
<div>
<input type="radio" ng-model="launchArray" name="group1" value="{{launchArray.name}}">
</div>
</div>
I want to display radio button with with username and email to display..
I tried ng-repeat also. It is not working.
Can u guide me what I doing wrong or what I can do?
Checkout this
<div class="modal-body">
<div>Please select an one data</div>
<div ng-repeat = 'item in launchArray'>
<input type="radio" ng-model="selected.value" name="group" ng-value="item.name">
<div> Name : {{item.name}}</div>
<div> Email : {{item.email}}</div>
</div>
</div>
<br>
<br>
<br>
<br>
<div >
<b>Selected Value :: </b>{{selected.value}}
</div>
var SSOUserResponse = [
{
"UserName": "se",
"FirstAndLastName": "Sam ",
"EmailAddress": "segfgf#x.net"
},
{
"UserName": "se2",
"FirstAndLastName": "Joe ", //
"EmailAddress": "se266#gmail.com" //
}
];
if (SSOUserResponse.length > 1) {
var launchArrayVal = [];
for (var i = 0; i < SSOUserResponse.length;i++){
launchArrayVal.push(
{ name: SSOUserResponse[i].UserName, email: SSOUserResponse[i].EmailAddress }
);
}
$scope.launchArray = launchArrayVal;
$scope.selected = {value: null};
}
You want to show one radio button per result, right?
This is when you would use ng-repeat. You didn't mention what the problem was when you used ng-repeat.
Currently, in your template, you're doing {{launchArray.name}} which won't work, since launchArray is an array... it doesn't have a name property.
Using ng-repeat, you loop over each item in launchArray and render a radio button each time:
<div class="modal-body">
<div>Please select an one data</div>
<div ng-repeat="item in launchArray">
<input type="radio" name="group1" value="{{item.name}}">
<span>{{item.name}} ({{item.email}})</span>
</div>
</div>

How do I get the values of checkboxes when using ng-repeat?

Code in file view.html:
<label ng-repeat = "agents in acesslevel |filter:{acesslevel: 'Agent'}">
<div class="col-xs-2">
<input type= "checkbox"
ng-model="agentsSelected"
checklist-value="agents.name"
ng-true-value=agents ng-false-value="'NO'">
{{agents.name}}
</div>
</label>
Where acesslevel is JSON format data I'm getting from my database.
For example,
{
"acesslevel": "Quality",
"dob": "1995-02-03",
"name": "anjali",
"password": "tanya",
"username": "anju",
"createdAt": "2014-07-02T16:26:26.816Z",
"updatedAt": "2014-07-02T16:26:26.816Z",
"id": "53b432b230aaa394278522ca"
},
{
"acesslevel": "Agent",
"dob": "1995-02-03",
"name": "christopher",
"password": "tanya",
"username": "anju",
"createdAt": "2014-07-02T16:26:48.170Z",
"updatedAt": "2014-07-02T16:26:48.170Z",
"id": "53b432c830aaa394278522cb"
}
This particular code in HTML is displaying the names of agents in acesslevel (in above case it would display christopher)
How would I get the value of the selected checkbox in the controller?
I want to insert this selected agent's data in a new table in my database server.
The problem is that you are using ng-model which binds to (what I suppose is) an array, but Angular expects a Boolean value (true or false).
If you instead bind to a property of the instances of your filtered accesslevel array you can extract that data later in your controller
<label ng-repeat = "agents in acesslevel |filter:{acesslevel: 'Agent'}">
<div class="col-xs-2">
<input type= "checkbox"
ng-model="agents.isSelected" <!-- bind to another value -->
checklist-value="agents.name"
ng-true-value="agents"
ng-false-value="'NO'">
{{agents.name}}
</div>
</label>
Your controller can access this property later if you for instance have a method to submit values to your backend.
$scope.submit = function() {
var selectedAgents = [];
angular.forEach($scope.acesslevel, function (agent) {
if (agent.acesslevel == 'Agent' && agent.isSelected) {
selectedAgents.push(agent);
}
});
// Here you can make calls to your backend with the selectedAgents variable.
};

Categories

Resources