Home > Software design >  How to fetch data from API with user input function
How to fetch data from API with user input function

Time:01-13

I'm new to APIs. I want to make a flight search API and I have a validation function and then I want to fetch the data based on the user input (which are still airport codes instead of city names). But when I console.log the fetchFlights like this: fetchFlights(AAR, BAJ, economy then I get an error saying that AAR is not defined, but the API works on airport codes. I have tried several ways to solve this but nothing so far did the job. i also tried:; fetchFlights(depAirport, arrAirport, travelClass) and that is in the code and that gave the same error.

When I do this: fetchFlights("AAR", "BAJ", "Economy") I get: GET https://google-flights-search.p.rapidapi.com/search?departure_airport_code=AAR"&arrival_airport_code=BAJ&flight_class=Economy 500 (Internal Server Error)

Does anyone know how I could get the data? Thanks a lot in advance!

function validateForm() {
  let depAirp = document.getElementById("field").value;
  let arrAirp = document.getElementById("field2").value;
  let travelCl = document.getElementById("field3").value;

  if (depAirp.value == null || data == '' || arrAirp.value == null || data == '' || travelCl.value == null || data == '') {
    document.getElementById("errorMessage2").innerHTML = "Please fill all the fields";
  } else {
    return 'true';
  }
}

function fetchFlights(depAirport, arrAirport, travelClass) {
  validateForm()

  fetch(`https://google-flights-search.p.rapidapi.com/search?departure_airport_code=${depAirport}"&arrival_airport_code=${arrAirport}&flight_class=${travelClass}`, {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "google-flights-search.p.rapidapi.com",
        "x-rapidapi-key": "283ff4e872msh5329c2c6fdca6d0p1655aejsnbaa6f9870616"
      }
    })

    .then(response => response.json())
    .then(json => {
      console.log(json.flights);
    })

}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="style.css" />
  <title>Flight Explorer</title>
</head>

<body>
  <div >
    <img  src="https://static.thenounproject.com/png/3782905-200.png" alt="" />
  </div>
  <form id="form" onsubmit="validateForm()">
    <p >Depart from</p>
    <input value="" id="field" type="text" placeholder="" autocomplete="off" />

    <p >Destination</p>
    <input id="field2" type="text" placeholder="" autocomplete="off" />

    <p>Departing Date</p>
    <input id="field3" type="text" placeholder="" autocomplete="off" />
    <small id="errorMessage2">s</small>
    <button  type="submit">Find flights</button>
  </form>
  </div>
  </div>

  <div id="results">
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
  </div>

  <div id="final-results"></div>
</body>

</html>

CodePudding user response:

The error from when you try to run the code in the Console is because you're passing variable names into the function in places of values, but those variables don't exist, so JS cannot use them to pass in a real value. It looks like you didn't realise that literal strings need to have quote marks around then. Running

fetchFlights('AAR', 'BAJ', 'economy')

resolves that particular problem.


Meanwhile, there are a few issues with the actual form itself:

  1. Your code never actually calls the fetchFlights function, even when the validation passed
  2. You don't prevent the form from doing a default postback, so the fetch code can never run
  3. There's a typo in the API URL template (a stray " which doesn't belong)
  4. It's recommended to use unobtrusive event handler syntax using addEventListener rather than inline event handlers within the HTML markup.
  5. You don't actually need your custom validation code because you can just set required attributes on all the input fields
  6. Your Date field doesn't match the "Travel Class" value you're sending to the API. I changed the wording of the label on the form.

This version fixes those issues:

var frm = document.querySelector("#form");
form.addEventListener("submit", function(event) {
  event.preventDefault(); //prevent a normal submit, to allow JS code to run
  fetchFlights();
});

function fetchFlights(depAirport, arrAirport, travelClass) {
  let depAirp = document.querySelector("#field").value;
  let arrAirp = document.querySelector("#field2").value;
  let travelCl = document.querySelector("#field3").value;

  fetch(`https://google-flights-search.p.rapidapi.com/search?departure_airport_code=${depAirport}&arrival_airport_code=${arrAirport}&flight_class=${travelClass}`, {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "google-flights-search.p.rapidapi.com",
        "x-rapidapi-key": "283ff4e872msh5329c2c6fdca6d0p1655aejsnbaa6f9870616"
      }
    })
    .then(response => response.json())
    .then(data => {
      console.log(JSON.stringify(data));
    });
}
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="style.css" />
  <title>Flight Explorer</title>
</head>

<body>
  <div >
    <img  src="https://static.thenounproject.com/png/3782905-200.png" alt="" />
  </div>
  <form id="form">
    <p >Depart from</p>
    <input value="" id="field" type="text" placeholder="" autocomplete="off" required />

    <p >Destination</p>
    <input id="field2" type="text" placeholder="" autocomplete="off" required />

    <p>Travel Class</p>
    <input id="field3" type="text" placeholder="" autocomplete="off" required/>
    <button  type="submit">Find flights</button>
  </form>
  </div>
  </div>

  <div id="results">
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
  </div>

  <div id="final-results"></div>
</body>

</html>

CodePudding user response:

  • You are passing parameters where you should not and vice versa
  • You also get values and test the value.value
  • Also you tested data which does not exist
  • There was a " in the URL that does not belong there
  • Lastly I change date to travel class in the form You need to add the date back somehow I think, but that is described in their API
  • I get invalid API key but the code will work much better than yours

This is likely what you MEANT to do

function fetchFlights(depAirport, arrAirport, travelClass) {
  fetch(`https://google-flights-search.p.rapidapi.com/search?departure_airport_code=${depAirport}&arrival_airport_code=${arrAirport}&flight_class=${travelClass}`, {
      "method": "GET",
      "headers": {
        "x-rapidapi-host": "google-flights-search.p.rapidapi.com",
        "x-rapidapi-key": "283ff4e872msh5329c2c6fdca6d0p1655aejsnbaa6f9870616"
      }
    })

    .then(response => response.json())
    .then(json => {
      console.log(json.flights);
    })

}
window.addEventListener("load", function() { // when page loads and page elements are available
  document.getElementById("form").addEventListener("submit", function(e) {
    e.preventDefault(); // stop submission

    let depAirp = document.getElementById("field").value;
    let arrAirp = document.getElementById("field2").value;
    let travelCl = document.getElementById("field3").value;
    if (depAirp == "" || arrAirp == "" || travelCl == "") {
      document.getElementById("errorMessage2").innerHTML = "Please fill all the fields";
    } else {
      fetchFlights(depAirp, arrAirp, travelCl)
    }
  })
})
<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <link rel="stylesheet" href="style.css" />
  <title>Flight Explorer</title>
</head>

<body>
  <div >
    <img  src="https://static.thenounproject.com/png/3782905-200.png" alt="" />
  </div>
  <form id="form">
    <p >Depart from</p>
    <input value="" id="field" type="text" placeholder="" autocomplete="off" />

    <p >Destination</p>
    <input id="field2" type="text" placeholder="" autocomplete="off" />

    <p>Travel class</p>
    <input id="field3" type="text" placeholder="" autocomplete="off" />
    <small id="errorMessage2"></small>
    <button  type="submit">Find flights</button>
  </form>
  </div>
  </div>

  <div id="results">
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
    <div >
    </div>
  </div>

  <div id="final-results"></div>
</body>

</html>

  •  Tags:  
  • Related