I'm trying to create a program that allows a user to input a number and fetches the movie data from an API by accessing the id index, so for example if I wanted to access the 3rd ID of the API, it would fetch all the elements from "https://my-json-server.typicode.com/daijonbereola/restful-api-react/movies/3". So far, no movie has been found and am not sure what is wrong with my Javascript. Here it is pasted below:
<form>
<input type="number" id="inputId" placeholder="Enter a number"/>
<input type="button" id="fetchId" value="Fetch Movie" class="btn btn-primary"/>
</form>
<script>
let id = document.getElementById("inputId").value;
let fetchId = document.getElementById("fetchId");
fetchId.addEventListener("click", selectHandler);
function selectHandler() {
// Instantiate an new XHR Object
const xhr = new XMLHttpRequest();
// Open an obejct (GET/POST, PATH,
// ASYN-TRUE/FALSE)
xhr.open("GET",
`https://my-json-server.typicode.com/daijonbereola/restful-api-react/movies/${id}`, true);
// When response is ready
xhr.onload = function () {
if (this.status === 200) {
// Changing string data into JSON Object
obj = JSON.parse(this.responseText);
// Getting the element
let list = document.getElementById("list");
id = obj.id;
console.log(id);
if(id){
str = ""
str +=
`
<div style="padding: 5px 5px;">
<a href=${obj.url}>${obj.title}</a>
<image style="max-width: 60%;"src=${obj.image} alt = "movie poster"/>
</div>
`;
list.innerHTML = str;
} else{
str = ""
str += `<p>Movie not found...Please try again</p>`;
list.innerHTML = str;
}
}
else {
console.log("File not found");
}
}
xhr.send();
}
</script>