1

I am trying to use the Unsplash API to generate images using a user's input. So far I've been able to retrieve images when query= is hardcoded but I want the results to vary based on what the user types and submits into the query. Below I've hardcoded "dog" as the query input.

Here is my code so far:

var client_id = "fcbcd3e60e7f6615d0e5c64ab8e830d9695c4c30a74586e8d234f9835923ad75";

$("#fieldsubmit").click(function(){
  query = $("#query").val();
})

$.getJSON('https://api.unsplash.com/search/photos?page=1&query=dog&client_id=fcbcd3e60e7f6615d0e5c64ab8e830d9695c4c30a74586e8d234f9835923ad75', function(data) {
  console.log(data);

  var imageList = data.results;
  $.each(imageList, function(i, val) {

    var image = val;
    var imageURL = val.urls.regular;
    var imageWidth = val.width;
    console.log(imageURL);

  $('.grid').append('<div class="image"><img src="'+ imageURL +'"</div>')

  });
});

1 Answer 1

2

Either put the JSON call in a function to be called in the callback of the click handler, or add it to the callback itself (like I've done below), and use a template literal to embed the variables right into the string.

$("#fieldsubmit").click(function(){
  const query = $("#query").val();
  const endpoint = 'https://api.unsplash.com/search/photos';
  const page = 1;
  $.getJSON(`${endpoint}?page=${page}&query=${query}&client_id=${client_id}`, function(data) {
    // ...
   });
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.