Autofill state and city based on zip code input using Sepomex API - javascript

I am trying to autofill city and state fields based on zip code input using sepomex API (for Mexico), on a site in corvid by wix, which is based on javascript but I think there is something wrong in the line json.response[0]["ciudad"].
$w.onReady(function () {
$w("#input1").onInput(() =>{
let zipcode = $w("#input1").value;
$w("#input2").value = "";
$w("#input3").value = "";
if (zipcode.length === 5) {
let apiUrl = "";
apiUrl = "https://api-sepomex.hckdrk.mx/query/info_cp/";
fetch(apiUrl + zipcode, {method: 'get'})
.then((httpResponse) => {
if (httpResponse.ok) {
return httpResponse.json();
}
else{
return Promise.reject("fetch was not successful")
}
})
.then((json) => {
console.log(json);
let response = json.response;
$w("#input10").value = json.response[0]["ciudad"];
$w("#input11").value = json.response[0]["estado"];
$w("#text148").collapse();
})
.catch(() =>{
$w("#text148").expand()
})
}
})
I can't display any data
There is the output on API
[
{
"error": false,
"code_error": 0,
"error_message": null,
"response": {
"cp": "44110",
"asentamiento": "Vallarta Poniente",
"tipo_asentamiento": "Fraccionamiento",
"municipio": "Guadalajara",
"estado": "Jalisco",
"ciudad": "Guadalajara",
"pais": "México"
}
}
]

change code inside second promise to.
.then((json) => {
let response = json[0].response;
$w("#input10").value = response.ciudad;
$w("#input11").value = response.estado;
$w("#text148").collapse();
})
now it should work

Solved
.then((json) =>{
let response = json[0].response;
$w("#input11").value = json[0].response["ciudad"];
$w("#input10").value = json[0].response["estado"];
$w("#text148").collapse();
})

Related

How can i make this reset button function work?

I am working on a very simple Weather API for practice and I just can't find a solution to make this resetFunc not be undefined / not a function.
I am loking for a way to make this function for the reset button not be undefined / not a function. I am attempting to make this reset function resetFunc() for the resetbtn only work after the displayExecuted flag becomes true, it keeps making the newText text node undefined.
I've tried with newText in both global and local scope.
let newText
let weatherDisplay;
let displayExecuted = false;
function getWeather() {
let resetbtn = document.getElementById(`resetbtn`)
let wbutton = document.getElementById(`wbutton`)
let weatherText = document.getElementById('w')
if (navigator.geolocation) {
navigator.geolocation.getCurrentPosition(position => {
const latitude = position.coords.latitude;
const longitude = position.coords.longitude;
const endpoint = `https://api.open-meteo.com/v1/forecast?latitude=${latitude}&longitude=${longitude}&hourly=temperature_2m&current_weather=true`
fetch(endpoint)
.then(res => res.json())
.then(data => {
console.log(data)
const weather = data['current_weather'].temperature
console.log(weather)
newText = document.createTextNode(`${weather}`)
weatherDisplay = function weatherDisplay() {
if (!displayExecuted) {
weatherText.querySelector('p').append(newText.nodeValue + " "+'degrees') }
displayExecuted = true
}
resetFunc = function resetFunc () {
if (displayExecuted === true) {
newText.nodeValue = " "
}
}
})
.catch(error => {
console.error("Error fetching data:", error)
})
.catch(error => {
console.error("Error fetching data", error)
})
})
wbutton.addEventListener(`click`,weatherDisplay,{once: true})
resetbtn.addEventListener(`click`,resetFunc)
} else {
console.error('Geolocation not supported in this browser')
}}
getWeather()
I've tried global variables and also tried formatting the functions in different scopes. I also want to add that I'm a beginner programmer, so please don't make fun of this code too much.

posting comments using api - invalid date

I am trying to build a form with comments. Comments are loaded using API and also new comments are posted to the API if submitted using two input fields and a submit button. The process is working, however the date of the comments writes "invalid date" when posted, but after refreshing the page the date is correct. My question is if anyone knows what could be the issue here? So to post a new comment, you have to input a name and the comment, date should be generated automatically. Thank you everyone. This is my js code below
axios
.get(showUrl + "?api_key=" + apiKey)
.then((response) => {
commentArray = response.data;
commentArray.forEach((commentContainer) => {
displayComment(commentContainer);
console.log("something")
})
})
.catch(error => {
console.log(error);
})
let commentArray = [];
function displayComment(arr) {
let commentContainer = document.createElement("div");
commentContainer.classList.add("comments__posted-container");
let roundLogo = document.createElement("div");
roundLogo.classList.add("comments__grey-round-logo");
let addedComments = document.createElement("div");
addedComments.classList.add("comments__added");
let nameDate = document.createElement("div");
nameDate.classList.add("name-date");
let nameUser = document.createElement("h4");
nameUser.innerText = arr.name;
let dateUser = document.createElement("p");
dateUser.classList.add("comments__added-date");
dateUser.innerText = new Date(Number(arr.timestamp)).toLocaleDateString();
let commentUser = document.createElement("p");
commentUser.innerText = arr.comment;
inputComment.appendChild(commentContainer);
commentContainer.appendChild(roundLogo);
commentContainer.appendChild(addedComments);
addedComments.appendChild(nameDate);
addedComments.appendChild(commentUser);
nameDate.appendChild(nameUser);
nameDate.appendChild(dateUser);
}
commentArray.forEach((commentContainer) => {
displayComment(commentContainer);
})
console.log(commentArray)
let formComment = document.querySelector(".comments__form")
let today = new Date();
formComment.addEventListener('submit', (event) => {
event.preventDefault();
let nameInput = event.target.name.value;
let commentInput = event.target.comment.value;
axios
.post(showUrl + "?api_key=" + apiKey, {
name: nameInput,
comment: commentInput,
// timestamp: today.toLocaleDateString(),
})
.then((response) => {
axios
.get(showUrl + "?api_key=" + apiKey)
.then((response) => {
let comments = response.data;
comments.innerText = "";
commentContainer(comments);
})
})
.catch((error) => {
});
if (nameInput && commentInput) {
commentArray.unshift({
name: nameInput,
comment: commentInput,
date: today.toLocaleDateString(),
// today: `${Date.now()}`
})
displayComment(commentArray[0])
}
formComment.reset()
})

How to consume one API endpoint which requires data from another API endpoint (dog.ceo)?

how to consume from one api with another api.
var url_1 = 'https://dog.ceo/api/breeds/list/all';
fetch(url_1)
.then( response => response.json())
.then(data => {
const breeds = data.message;
var arr = [];
for (var b in breeds) {
arr.push({
breed : b,
subBreeds : [
breeds[b][0]
],
images : [{
url: ''
}]
})
}
I also have this other api, from where I extract the images of each breed of dog, but here you need the variable that would be the name of the dog's breed.
var url_2 = 'https://dog.ceo/api/breed/{breed_name}/images';
fetch(url_2)
.then( response => response.json())
.then(data => {
const images = data.message;
var arr_images = [];
for (var i in images) {
arr_images.push({
images : [{
url: images[i]
}]
})
}
So what I don't know, how can I join to send the name of the dog's breed to the second api to consume it?
And how can I join the arrangement of the images with the arrangement above?
it should be something like this
{ "breed": "Hound",
"subBreeds": [
"subBreedA",
"subBreedB",
"subBreedC"
],
"images":[
{"url":"http://some.url.com"},
{"url":"http://some.other.url"}
]
}
I hope I have been clear, thanks for your help, I will be very grateful.
I would split it up into separate functions so that you can focus on one part at a time. Then, combine them to get all of the data that you want. In this way, you can also re-use each function in case you want to use the data in a different way:
TS Playground
// dog.ceo API
async function fetchDogApiResult (apiPath) {
const response = await fetch(`https://dog.ceo/api/${apiPath}`);
if (!response.ok) throw new Error(`Response not OK (${response.status})`);
const data = await response.json();
if (data.status !== 'success') throw new Error('Response not successful');
return data.message;
}
async function fetchBreeds () {
return fetchDogApiResult('breeds/list/all');
}
async function fetchSubBreeds (breed) {
return fetchDogApiResult(`breed/${breed}/list`);
}
async function fetchImages (breed, subBreed) {
return fetchDogApiResult(`breed/${breed}${subBreed ? `/${subBreed}` : ''}/images`);
}
async function fetchDogData () {
const breeds = await fetchBreeds();
return Promise.all(Object.entries(breeds).map(async ([breed, subBreeds]) => ({
breed,
subBreeds,
images: (await fetchImages(breed)).map(url => ({url})),
})));
}
(async () => {
const dogData = await fetchDogData();
console.log(JSON.stringify(dogData));
})();
You can use async/await for call second api in second then of first api, after you get data from second api, you can use for loop for them. like this
var url_1 = 'https://dog.ceo/api/breeds/list/all';
fetch(url_1)
.then( response => response.json())
.then(async data => {
const breeds = data.message;
const resUrl2 = await fetch(url_2)
const dataUrl2 = await resUrl2.json()
var arr = [];
for (var b in breeds) {
arr.push({
breed : b,
subBreeds : [
breeds[b][0]
],
images : [{
url: ''
}]
})
}
const images = dataUrl2.message;
var arr_images = [];
for (var i in images) {
arr_images.push({
images : [{
url: images[i]
}]
})
}
})

Vue js/Javascript Objects.assign() not working

I need to concatenate two objects in Vue/Javascript and order the resulting one by date field but I'm getting empty results using Object.assign().
I've tried other methods searching on StackOverflow but nothing has worked as expected. Mostly I get empty results
methods: {
getAllMessages: function () {
// console.log(this.myID);
let distinct = '';
firebase.firestore().collection('private-messages').where('memberID', '==', `${this.myID}`)
.orderBy('date').onSnapshot(res => {
let members = [];
res.forEach(doc => {
members.push(doc.data().uid);
});
distinct = Array.from(new Set(members));
// console.log(distinct);
this.getUserToTalk(distinct);
});
},
getMyMessages: function (memberID) {
let myMessages = [];
firebase.firestore().collection('private-messages').where('uid', '==', `${this.myID}`).where('memberID', '==', `${memberID}`)
.orderBy('date').onSnapshot(res => {
res.forEach(doc => {
myMessages.push(doc.data());
});
});
// this.myMessages = myMessages;
return myMessages;
},
getMessages: function (memberID) {
let messages = [];
firebase.firestore().collection('private-messages').where('uid', '==', `${memberID}`).where('memberID', '==', `${this.myID}`)
.orderBy('date').onSnapshot(res => {
res.forEach(doc => {
messages.push(doc.data());
});
});
// this.memberMessages = messages;
return messages;
},
getUserToTalk: function (memberID) {
axios.post('http://localhost/backend/getMemberToTalk.php', {
"token": token,
"whoToTalkTo": memberID,
}).then(response => {
if (response.data != "Error getting user data and tour") {
let joinedData = []
// console.log(response.data);
response.data.forEach(res => {
let id = res.memberID;
let messages = this.getMessages(id);
// console.log(messages);
let myMessages = this.getMyMessages(id);
// console.log(myMessages);
// if I use below assignment I can get the messages, but I need to concat them.
// so, if I use let conversation = Object.assign({}, messages, myMessages);
// or let conversation = { ...messages, ...myMessages }
// the result is always empty.
let talk1 = Object.assign(messages);
let talk2 = Object.assign(myMessages);
console.log(talk, talkmy);
let data = {
memberID: res.memberID,
memberProfileImg: res.memberProfileImg,
memberName: res.memberName,
memberLastname: res.memberLastname,
memberCity: res.memberCity,
memberState: res.memberState,
memberMessages: messages,
myMessages: myMessages,
// messages: conversation
}
joinedData.push(data);
});
// console.log(joinedData);
this.memberData = joinedData;
// console.log(this.memberData);
} else {
console.log(response.data);
}
}).catch(error => {
console.log(error);
});
},
}
These are the full objects and in the example below I need to add the object from messages.js:140 as a "third index" in messages.js:137 resulting in
0:{...}
1:{...}
2:{...}
and then
3:{...}

Destructuring the API https://randomuser.me/api/ to grab title, last name, and first name also large photo of the user profile returned by the API

I'm trying to grab some data(title, last name, first name and also large photo of the user profile returned by the API.) from the API https://randomuser.me/api/, which seem to not be working.
const displayUserPhotoAndName = (data) => {
if(!data) return;
// add your code here
let {results} = data;
let [profile] = results;
document.querySelector('h2').textContent = profile.name.title +' '+ profile.name.last +' '+ profile.name.first;
document.querySelector('img').src = profile.picture.large;
displayExtraUserInfo(profile);
clearNotice();
};
const getAUserProfile = () => {
const api = 'https://randomuser.me/api/';
// make API call here
fetch(api)
.then((resp) => resp.json())
.then(data => {displayUserPhotoAndName()});
notify(`requesting profile data ...`);
};
const displayBirthdate = ({dob = 'dob'}) => {
document.querySelector('.details').textContent = dob.age;
}
const displayPhone = ({phone = 'phone', cell = 'cell'}) => {
document.querySelector('.details').textContent = phone + ', ' + cell;
}
const displayAddress = ({location = 'location'}) => {
document.querySelector('.details').textContent = location.street + ', ' + location.city + ', ' + location.state;
}
You are passing the data to the function.Do like below
const getAUserProfile = () => {
const api = 'https://randomuser.me/api/';
// make API call here
fetch(api)
.then((resp) => resp.json())
.then(data => {displayUserPhotoAndName(data)}); //this line is changed
notify(`requesting profile data ...`);
};
Here is the line that will get all the required properties
let {results:[{ name: { title , first , last } , picture:{ large } }]} = data;
Here is how you can do it and also handle bad data with default values. Also, do not forget to pass data to your function in the then callback:
const display = data => {
const { results: [{ name: { title, first, last } = {}, picture: { large } = {} }] = [] } = data || {};
console.log(title, first, last, large);
};
fetch('https://randomuser.me/api/').then(r => display(r.json()));

Categories

Resources