Home > Enterprise >  Display only relevant results from API call
Display only relevant results from API call

Time:01-20

I need a bit of help with a project I am doing for a course. The task is to display results from three API's in a results area on a page but the page must only display one set of API results at a time.

The initial state on page load looks like this: enter image description here

Then when a submit button is clicked the result appears then when the next submit button is clicked the result for the previous API call disappears and the result for the API just called is displayed.

I'm able to get all three API's to return results individually with the result of the previous call remaining on the page but I can't seem to work out how to have nothing showing in the results section on page load then only have the relevant API call results showing. I've tried setting the CSS for the three elements to display: none then trying to show the relevant element within the jQuery click event handler using .show() but this isn't working.

Again any help would be greatly appreciated.

My code is as follows:

index.html

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="libs/css/style.css">
</head>

<body>
    <table>
        <tr>
            <th>API Name</th>
            <th>API Description</th>
            <th></th>
        </tr>
        <tr>
            <td>1. Timezone</td>
            <td><p id="tabledescriptions">Description</p>
                <p>The timezone at the given longtitute and latitude.</p>
                <label for="longitude">Enter the Longitude: </label>
                <input type="text" id="long" name="longitude">
                <label for="latitude">Enter the Latitude: </label>
                <input type="text" id="lat" name="latitude">
            </td>
            <td><button id="buttonrun1">Submit</button></td>
        </tr>
        <tr>
            <td>2. Ocean Info</td>
            <td id=""><p id="tabledescriptions">Description</p>
                <p>The nearest Ocean to the longitude & latitude given above.</p>
                <label for="longitude1">Enter the Longitude: </label>
                <input type="text" id="long1" name="longitude1">
                <label for="latitude1">Enter the Latitude: </label>
                <input type="text" id="lat1" name="latitude1">
            </td>
            <td><button id="buttonrun2">Submit</button></td>
        </tr>
        <tr>
            <td>3. Weather ICAO</td>
            <td><p id="tabledescriptions">Description</p>
            <p>Display's the weather at a given Airport by its ICAO airport code.</p>
            <label for="ICAOCode">Enter ICAO Code</label>
            <select name="ICAOCode" id="selAirport">
                <option value="yssy">Sydney Kingsford Smith International</option>
                <option value="egll">London Heathrow Airport</option>
            </select>
            </td>
            <td><button id="buttonrun3">Submit</button></td>
        </tr>
        <tr colspan="3">
            <td id="timezoneRes"><p id="tabledescriptions">Result of Timezone API Call</p>
                <p>Sunrise:</p><p id="sunrise"></p>
                <p>Sunset:</p><p id="sunset"></p>
                <p>Country:</p><p id="country"></p>
                <p>Time Zone:</p><p id="timeZone"></p>
                <p>Time Now:</p><p id="timeNow"></p>
            </td>
           
            <td id="weatherRes"><p id="tabledescriptions">Result of Weather by ICAO Code Call</p>
                <p>Airport Name: </p><p id="airName"></p>
                <p>Wind Speed: </p><p id="windSp"></p>
                <p>Temperature (Celcius): </p><p id="temp"></p>
                <p>Wind Direction: </p><p id="windDir"></p>
            </td>

            
            <td id="oceanRes"><p id="tabledescriptions">Result of Ocean API Call</p>
                <p>Ocean: </p><p id="ocean"></p>
            </td>
        </tr>
    </table>
    <script type="application/javascript" src="libs/js/jquery-2.2.3.min.js"></script>
    <script type="application/javascript" src="libs/js/main.js"></script>
</body>

<footer>


</footer>

main.js

$('#buttonrun1').on('click', function() {

$('#timezoneRes').show();
$('#weatherRes').hide();
$('#oceanRes').hide();


$.ajax({
  url: "libs/php/getTimeZone.php",
  type: 'POST',
  dataType: 'json',
  data: {
    longitude: $('#long').val(),
    latitude: $('#lat').val()
  },
  success: function(result) {

    console.log(JSON.stringify(result));

    if (result.status.name == "ok") {

      $('#sunrise').html(result.data.sunrise);
      $('#sunset').html(result.data.sunset);
      $('#country').html(result.data.countryName);
      $('#timeZone').html(result.data.timezoneId);
      $('#timeNow').html(result.data.time);

    }
  
  },
  error: function(jqXHR, textStatus, errorThrown) {
    // your error code
  }
}); 


});

$('#buttonrun2').on('click', function() {

  $.ajax({
    url: "libs/php/getOcean.php",
    type: 'POST',
    dataType: 'json',
    data: {
  longitudea: $('#long1').val(),
  latitudea: $('#lat1').val()
},
success: function(result) {

  console.log(JSON.stringify(result));

if (result.status.name == "ok") {

    $('#ocean').html(result.data.ocean.name);


  }

},
error: function(jqXHR, textStatus, errorThrown) {
  // your error code
}


}); 

});

  $('#buttonrun3').on('click', function() {

    $.ajax({
      url: "libs/php/getWeather.php",
      type: 'POST',
      dataType: 'json',
      data: {
        icaoCode: $('#selAirport').val()
      },
      success: function(result) {

        console.log(JSON.stringify(result));
    
      if (result.status.name == "ok") {

          $('#airName').html(result.data.weatherObservation.stationName);
          $('#windSp').html(result.data.weatherObservation.windSpeed);
          $('#temp').html(result.data.weatherObservation.temperature);
          $('#windDir').html(result.data.weatherObservation.windDirection);
        }
      
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // your error code
      }
    }); 

  });

CodePudding user response:

On the onclick events for button2 and button3 you need to hide/show the results like you are doing for button1, for example:

$('#buttonrun2').on('click', function() {

$('#timezoneRes').hide();
$('#weatherRes').hide();
$('#oceanRes').show();
}

I've tested in codepen.io and its working as expected.

If you would like to show none by default just set

style="display:none"

on each of the columns by default and show when necessary.

CodePudding user response:

What I was able to understand is that you just need to show one API result at a time and hide the other, so for that, you need to give some common class to all result containers and in your ajax success hide that class and just show the current one

<!DOCTYPE html>
<html>
<head>
    <link rel="stylesheet" type="text/css" href="libs/css/style.css">
</head>

<body>
    <table>
        <tr>
            <th>API Name</th>
            <th>API Description</th>
            <th></th>
        </tr>
        <tr>
            <td>1. Timezone</td>
            <td><p id="tabledescriptions">Description</p>
                <p>The timezone at the given longtitute and latitude.</p>
                <label for="longitude">Enter the Longitude: </label>
                <input type="text" id="long" name="longitude">
                <label for="latitude">Enter the Latitude: </label>
                <input type="text" id="lat" name="latitude">
            </td>
            <td><button id="buttonrun1">Submit</button></td>
        </tr>
        <tr>
            <td>2. Ocean Info</td>
            <td id=""><p id="tabledescriptions">Description</p>
                <p>The nearest Ocean to the longitude & latitude given above.</p>
                <label for="longitude1">Enter the Longitude: </label>
                <input type="text" id="long1" name="longitude1">
                <label for="latitude1">Enter the Latitude: </label>
                <input type="text" id="lat1" name="latitude1">
            </td>
            <td><button id="buttonrun2">Submit</button></td>
        </tr>
        <tr>
            <td>3. Weather ICAO</td>
            <td><p id="tabledescriptions">Description</p>
            <p>Display's the weather at a given Airport by its ICAO airport code.</p>
            <label for="ICAOCode">Enter ICAO Code</label>
            <select name="ICAOCode" id="selAirport">
                <option value="yssy">Sydney Kingsford Smith International</option>
                <option value="egll">London Heathrow Airport</option>
            </select>
            </td>
            <td><button id="buttonrun3">Submit</button></td>
        </tr>
        <tr colspan="3">
            <td id="timezoneRes" >
<p id="tabledescriptions">Result of Timezone API Call</p>
                <p>Sunrise:</p><p id="sunrise"></p>
                <p>Sunset:</p><p id="sunset"></p>
                <p>Country:</p><p id="country"></p>
                <p>Time Zone:</p><p id="timeZone"></p>
                <p>Time Now:</p><p id="timeNow"></p>
            </td>
           
            <td id="weatherRes" >
                <p id="tabledescriptions">Result of Weather by ICAO Code Call</p>
                <p>Airport Name: </p><p id="airName"></p>
                <p>Wind Speed: </p><p id="windSp"></p>
                <p>Temperature (Celcius): </p><p id="temp"></p>
                <p>Wind Direction: </p><p id="windDir"></p>
            </td>

            
            <td id="oceanRes" >
                <p id="tabledescriptions">Result of Ocean API Call</p>
                <p>Ocean: </p><p id="ocean"></p>
            </td>
        </tr>
    </table>
    <script type="application/javascript" src="libs/js/jquery-2.2.3.min.js"></script>
    <script type="application/javascript" src="libs/js/main.js"></script>
</body>

<footer>


</footer>

main.js

$('#buttonrun1').on('click', function() {
$(".result-container").hide();   
$.ajax({
  url: "libs/php/getTimeZone.php",
  type: 'POST',
  dataType: 'json',
  data: {
    longitude: $('#long').val(),
    latitude: $('#lat').val()
  },
  success: function(result) {

    console.log(JSON.stringify(result));

    if (result.status.name == "ok") {

      $('#sunrise').html(result.data.sunrise);
      $('#sunset').html(result.data.sunset);
      $('#country').html(result.data.countryName);
      $('#timeZone').html(result.data.timezoneId);
      $('#timeNow').html(result.data.time);

      $('#timezoneRes').show();

    }
  
  },
  error: function(jqXHR, textStatus, errorThrown) {
    // your error code
  }
}); 


});

$('#buttonrun2').on('click', function() {
$(".result-container").hide();  
  $.ajax({
    url: "libs/php/getOcean.php",
    type: 'POST',
    dataType: 'json',
    data: {
  longitudea: $('#long1').val(),
  latitudea: $('#lat1').val()
},
success: function(result) {

  console.log(JSON.stringify(result));

if (result.status.name == "ok") {

    $('#ocean').html(result.data.ocean.name);

    $('#oceanRes').show();
  }

},
error: function(jqXHR, textStatus, errorThrown) {
  // your error code
}


}); 

});

  $('#buttonrun3').on('click', function() {
    $(".result-container").hide();
    $.ajax({
      url: "libs/php/getWeather.php",
      type: 'POST',
      dataType: 'json',
      data: {
        icaoCode: $('#selAirport').val()
      },
      success: function(result) {

        console.log(JSON.stringify(result));
    
      if (result.status.name == "ok") {

          $('#airName').html(result.data.weatherObservation.stationName);
          $('#windSp').html(result.data.weatherObservation.windSpeed);
          $('#temp').html(result.data.weatherObservation.temperature);
          $('#windDir').html(result.data.weatherObservation.windDirection);
           $('#weatherRes').show();
        }
      
      },
      error: function(jqXHR, textStatus, errorThrown) {
        // your error code
      }
    }); 

  });

CodePudding user response:

Your code seems fine ... you just need to do it for all buttons ... you might want to create some kind of loop to automate if it gets too long. I've just changed the xhr calls to GET in order to use github, keep your calls as they are since they are working. Ask me in the comments if you need further explanations.

$('#timezoneRes').hide();
$('#weatherRes').hide();
$('#oceanRes').hide();
  
const load = {
  timezone: false,
  ocean: false,
  weather: false
};

$('#buttonrun1').on('click', function() {
  
  const loadData1 = function () {
    $.ajax({
      url: "https://gist.githubusercontent.com/rafaelcastrocouto/96febb53e336af025a54487929664069/raw/a904acc24371aa3120a4d784f8e1ec44731869ee/gistfile1.txt",
      type: 'GET',
      dataType: 'json',
      data: {
        longitude: $('#long').val(),
        latitude: $('#lat').val()
      },
      success: function(result) {

        console.log(JSON.stringify(result));

        if (result.status.name == "ok") {
          
          load.timezone = true;

          $('#sunrise').html(result.data.sunrise);
          $('#sunset').html(result.data.sunset);
          $('#country').html(result.data.countryName);
          $('#timeZone').html(result.data.timezoneId);
          $('#timeNow').html(result.data.time);

        }

      },
      error: function(jqXHR, textStatus, errorThrown) {
        // your error code
      }
    }); 
  }

  if (!load.timezone) loadData1();

  $('#timezoneRes').show();
  $('#oceanRes').hide();
  $('#weatherRes').hide();
  
});

$('#buttonrun2').on('click', function() {
  
  const loadData2 = function () {

    $.ajax({
      url: "https://gist.githubusercontent.com/rafaelcastrocouto/ae18e1af655a45ae14c7cb7c05066e42/raw/fe1eb28c629c6793d4ccd8a3c8505b72dbd32a81/ocean",
      type: 'GET',
      dataType: 'json',
      data: {
        longitudea: $('#long1').val(),
        latitudea: $('#lat1').val()
      },
      success: function(result) {

        console.log(JSON.stringify(result));

        if (result.status.name == "ok") {
          
          load.ocean = true;

          $('#ocean').html(result.data.ocean.name);


        }

      },
      error: function(jqXHR, textStatus, errorThrown) {
        // your error code
      }


    }); 
  }
  
  if (!load.ocean) loadData2();

  $('#timezoneRes').hide();
  $('#oceanRes').show();
  $('#weatherRes').hide();
  
});

$('#buttonrun3').on('click', function() {
  
  const loadData3 = function () {

    $.ajax({
      url: "https://gist.githubusercontent.com/rafaelcastrocouto/f991ff227f20643d8c6dfb525a072e18/raw/58a810188f976a5526327ca9627e09c17277d2cb/weather",
      type: 'GET',
      dataType: 'json',
      data: {
        icaoCode: $('#selAirport').val()
      },
      success: function(result) {

        console.log(JSON.stringify(result));

        if (result.status.name == "ok") {
          
          load.weather = true;

          $('#airName').html(result.data.weatherObservation.stationName);
          $('#windSp').html(result.data.weatherObservation.windSpeed);
          $('#temp').html(result.data.weatherObservation.temperature);
          $('#windDir').html(result.data.weatherObservation.windDirection);
        }

      },
      error: function(jqXHR, textStatus, errorThrown) {
        // your error code
      }
    }); 
  }
  
  if (!load.weather) loadData3();

  $('#timezoneRes').hide();
  $('#oceanRes').hide();
  $('#weatherRes').show();

});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
  <tr>
    <th>API Name</th>
    <th>API Description</th>
    <th></th>
  </tr>
  <tr>
    <td>1. Timezone</td>
    <td><p id="tabledescriptions">Description</p>
      <p>The timezone at the given longtitute and latitude.</p>
      <label for="longitude">Enter the Longitude: </label>
      <input type="text" id="long" name="longitude">
      <label for="latitude">Enter the Latitude: </label>
      <input type="text" id="lat" name="latitude">
    </td>
    <td><button id="buttonrun1">Submit</button></td>
  </tr>
  <tr>
    <td>2. Ocean Info</td>
    <td id=""><p id="tabledescriptions">Description</p>
      <p>The nearest Ocean to the longitude & latitude given above.</p>
      <label for="longitude1">Enter the Longitude: </label>
      <input type="text" id="long1" name="longitude1">
      <label for="latitude1">Enter the Latitude: </label>
      <input type="text" id="lat1" name="latitude1">
    </td>
    <td><button id="buttonrun2">Submit</button></td>
  </tr>
  <tr>
    <td>3. Weather ICAO</td>
    <td><p id="tabledescriptions">Description</p>
      <p>Display's the weather at a given Airport by its ICAO airport code.</p>
      <label for="ICAOCode">Enter ICAO Code</label>
      <select name="ICAOCode" id="selAirport">
        <option value="yssy">Sydney Kingsford Smith International</option>
        <option value="egll">London Heathrow Airport</option>
      </select>
    </td>
    <td><button id="buttonrun3">Submit</button></td>
  </tr>
  <tr colspan="3">
    <td id="timezoneRes"><p id="tabledescriptions">Result of Timezone API Call</p>
      <p>Sunrise:</p><p id="sunrise"></p>
      <p>Sunset:</p><p id="sunset"></p>
      <p>Country:</p><p id="country"></p>
      <p>Time Zone:</p><p id="timeZone"></p>
      <p>Time Now:</p><p id="timeNow"></p>
    </td>

    <td id="weatherRes"><p id="tabledescriptions">Result of Weather by ICAO Code Call</p>
      <p>Airport Name: </p><p id="airName"></p>
      <p>Wind Speed: </p><p id="windSp"></p>
      <p>Temperature (Celcius): </p><p id="temp"></p>
      <p>Wind Direction: </p><p id="windDir"></p>
    </td>


    <td id="oceanRes"><p id="tabledescriptions">Result of Ocean API Call</p>
      <p>Ocean: </p><p id="ocean"></p>
    </td>
  </tr>
</table>

  •  Tags:  
  • Related