Click here to Skip to main content
15,913,685 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
How do I get phone number details from a public API and display that on the webpage when I enter any number into the search box? Can you provide the general code?

What I have tried:

JavaScript
//button with id myBtn
let myBtn = document.getElementById("myBtn");

//div with id content
let content = document.getElementById("content");

/* function getData() {
  fetch("http://apilayer.net/api/validate")
    .then(res => return res.json();)
    .then((data) => {
      console.log(data);
    });
}
console.log(getData()); */

fetch("http://apilayer.net/api/validate")
  .then((res) => res.json())
  .then((data) => console.log(data));
Posted
Updated 22-Jun-21 22:27pm
v2

1 solution

If you're planning on making an API call using fetch() then you probably intend on sending the value across to the API. At the moment you're performing a simple GET request with no additional input, so that's probably not going to work.

You can use the fetch() document[^] as a starting point for what you're trying to accomplish. We're not going to build the code for you, but you have a good starting point with what you've already tried. You need to work out whether the API is expecting a JSON (application/json) request or a form (application/x-www-form-urlencoded).

JavaScript
// Sending a request as JSON
fetch('https://api.domain/path', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json'
  },
  body: JSON.stringify({
    phoneNumber: document.getElementById('..').value
  })
})
  .then(..)
  .catch(..)

// Sending a request as a form
const form = new FormData();
form.append('phoneNumber', document.getElementById('..').value);

fetch('https://api.domain/path', {
  method: 'POST',
  body: form
})
  .then(..)
  .catch(..)
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900