Week Nine Assignment:
HTTP Requests with Plant.ID API

Example Assignment

Plant Detection Form

The code overall handles:


document.getElementById("PD-image-upload")
.addEventListener("change", function(event) {
  var selectedFilesContainer = document.querySelector(".PD-selected-files");
  selectedFilesContainer.innerHTML = "";

  for (var i = 0; i < event.target.files.length; i++) {
    var file = event.target.files[i];
    var reader = new FileReader();

    reader.onload = function(event) {
      var image = document.createElement("img");
      image.src = event.target.result;

      var imageContainer = document.createElement("div");
      imageContainer.appendChild(image);

      var removeImage = document.createElement("span");
      removeImage.classList.add("remove-image");
      removeImage.innerHTML = "Remove";
      removeImage.addEventListener("click", function() {
        imageContainer.parentNode.removeChild(imageContainer);
      });

      imageContainer.appendChild(removeImage);
      selectedFilesContainer.appendChild(imageContainer);
    }

    reader.readAsDataURL(file);
  }
});

LOADING

Plant Health Assessment

  1. Obtain an API key from the Plant.ID API website. You can sign up for an API key at the Plant.ID API website.
  2. Replace the empty api_key value in the JavaScript code with your obtained API key.
  3. Implement the API request using the provided code. Use the fetch function or any other library that allows making HTTP requests. Make a POST request to the API endpoint 'https://api.plant.id/v2/health_assessment' with the following details:
    • Set the Content-Type header to 'application/json'.
    • Pass the data object, converted to a JSON string using JSON.stringify(), as the request body.
  4. Handle the API response by parsing the returned data and updating the HTML page accordingly. Create HTML elements dynamically using JavaScript and append them to the appropriate containers in the HTML structure.
  5. Implement error handling code inside the catch block to handle any errors that may occur during the API request.
  6. Customize the HTML structure and styles according to your requirements. Identify the appropriate HTML elements and containers for displaying the API results.
  7. Test the functionality by selecting multiple image files and submitting the form to trigger the API request.
  8. Optional: Implement additional features or enhancements to improve the user experience, such as displaying loading animations, error messages, or handling the removal of selected images.

LOADING